1
votes

I have a strange behaivor of the preg_match in PHP.

For checking a sql query, is there an unescaped assign of a value, I've wrote the following regexp, and piece of code. (See below).

The pattern:

 =[\s]*'[^'|^\\']*'[^']*'

The expected result

'val\'ue' //Result should be 0
'value' //Result should be 0
'val'ue' //Result should be 1!!!

So, I've checked it in Regex Coach (native regex tester on windows), and on an online regex tester, and I've get back the expected result.

Ok, so it's seems, my pattern is works. Now I am do it in PHP:

$values = array(
    "='val\'ue'",
    "='value'",
    "='val'ue'"
);
$pattern = "=[\s]*'[^'|^\\']*'[^']*'";
echo "Pattern is: " . $pattern . "<br>";
foreach ($values as $value) {
    echo "Value is: " . $value . "<br>";
    var_dump(preg_match("/" . $pattern . "/i", $value, $matches));
}

And guess what:

Pattern is: =[\s]*'[^'|^\']*'[^']*'

Value is: ='val\'ue'
int 1 //<------- THIS SHOULD BE ZERO!

Value is: ='value'
int 0

Value is: ='val'ue'
int 1

Maybe I am so tired, and make an obvious mistake, plese help mi out, what do I wrong.

1
i suggest you to use a different delimiter. Inside /, to match a single backslash, you need to put //// four or three backslashes. - Avinash Raj
In other words @AvinashRaj wants to say use: ~ and he will be happy :D - Rizier123
Tried with ~ or @, the result is the same. - vaso123
What do you mean by 0's and 1's? - Avinash Raj
for next to wich '? - vaso123

1 Answers

0
votes

This regex should work for you:

$pattern = "=\s*'(?:[^\\']*\\\\')*[^']*'(?=\\s|$)";
echo "Pattern is: " . $pattern . "\n";
foreach ($values as $value) {
    echo "Value is: " . $value . "\n";
    var_dump(preg_match("/" . $pattern . "/", $value, $matches));
}

Output:

Pattern is: ^=\s*'([^\']*\\')*[^']*'$
Value is: ='val\'ue'
int(1)
Value is: ='value'
int(1)
Value is: ='val'ue'
int(0)

RegEx Demo