0

I'm trying to get strings inside a quote. I'm using regex but i have problems with escaped quotes.

For example, i have this:

$var = "SELECT * FROM TABLE WHERE USERNAME='Carasuman'";
preg_match_all('~([\'"])(.*?)\1~s', $var, $result);
$new = preg_replace('~([\'"])(.*?)\1~s',"<#################>",$var);

The code Works perfect. I got a replaced value in $new and quoted value in $result[1]

$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>";
$result[1] = "Carasuman";

My problem is when i add a scaped quote inside quotes:

$var = "SELECT * FROM TABLE WHERE USERNAME='Carasuman\'s'";

I got this:

$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>'s";
$result[1] = "Carasuman\" //must be "Carasuman\'s";

How I can avoid this error and get $new and $result[1] like first example?:

$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>";
$result[1] = "Carasuman\'s";

Thanks!

1

3 Answers 3

1

for the match, you're never going to get Carasuman's without the \ as a single matched element since you can have match skip over chars within a single match. its either going to grab the Carasuman or Carasuman\'s

just use str_replace to get rid of the backslash

preg_match_all('~([\'"])(.*)\1~s', $var, $result);
$result[2] = str_replace('\\','',$result[2]);

for the replace, the ? in the (.*?) group makes it ungreedy, meaning it will stop at the first match. Remove the ? in (.*?) to make it greedy, meaning it will keep going until the last match

preg_replace('~([\'"])(.*)\1~s',"<#################>",$var);

Edit

Rather than doing the str_replace after the match on $result[2], it would probably be better to just do beforehand on the initial string like:

$var = str_replace("\\'","'",$var); 
preg_match_all('~([\'"])(.*)\1~s', $var, $result);
$new = preg_replace('~([\'"])(.*)\1~s',"<#################>",$var);

You still need to make your wildcard match greedy like (.*?) to (.*) in order to have the apostrophe in the name included in the match/replace instead of being counted as the terminating single quote

Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you do this:

$var = "SELECT * FROM TABLE WHERE USERNAME='" . mysql_real_escape_string($input) . "'";

I don't think you necessarily need to do regex. Also, mysql_real_escape_string properly escapes your inputs so you can just have $input = 'Carasuman\'s'; or $input = "Carasuman's";

1 Comment

I used the example of a SQL statement to make it more visible. Not necessarily be an SQL statement.
0

To match quoted strings, you could use the regex '\'.*?(?:\\\\.[^\\\\\']*)*\'' and four double quoted strings '".*?(?:\\\\.[^\\\\"]*)*"'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.