Reputation: 3388
I am trying to match all instances of the substring '${foo}' inside $content. I can match '{foo}' but not '${foo}' for some reason. Anyone know why?
$content="aaaa\${foo}bbbb\n";
echo $content; // aaaa${foo}bbbb
// THIS WORKS AS EXPECTED: matches all instances of substring '{foo}'
$result = preg_match_all("/(\{\w+\})/", $content, $matches);
if ($result === false) { die("NOT OK!"); }
echo "NUMBER OF MATCHES: ", $result, "\n";
var_dump($matches);
// THIS DOESN'T WORK AS EXPECTED: doesn't match instances of substring '${foo}'
$result = preg_match_all("/(\$\{\w+\})/", $content, $matches);
if ($result === false) { die("NOT OK!"); }
echo "NUMBER OF MATCHES: ", $result, "\n";
var_dump($matches);
Here is the output of this code. The first part outputs 1 matches, as expected, whereas the second part outputs 0 matches, but I was expecting 1 match:
aaaa${foo}bbbb
NUMBER OF MATCHES: 1
array(2) {
[0]=>
array(1) {
[0]=>
string(5) "{foo}"
}
[1]=>
array(1) {
[0]=>
string(5) "{foo}"
}
}
NUMBER OF MATCHES: 0
array(2) {
[0]=>
array(0) {
}
[1]=>
array(0) {
}
}
Thanks.
Upvotes: 0
Views: 1053
Reputation: 286
Use single quotes on your pattern.
Example:
$pattern = '/(AUTH|PENALTY|(?:\$LINE))/i';
$DETTYPE_VALUE = array_filter($data, function($a) use($pattern) {
return preg_match_all($pattern, $a['fine']);
});
Upvotes: 0
Reputation: 3388
Use single quotes so as to not have to double escape the $ sign. Only regular expression special characters need to be escaped when used in a regular expression in single quotes, apart from backslashes and single quotes which need to be escaped in any PHP string enclosed in single quotes. When using regular expressions only use double quotes when you need to embed a variable inside your regular expression (in which case other characters may need to be escaped as well as the other answers demonstrate).
Hence the following works:
$content="aaaa\${foo}bbbb\n";
echo $content; // aaaa${foo}bbbb
// THIS WORKS AS EXPECTED: matches all instances of substring '{foo}'
$result = preg_match_all('/(\{\w+\})/', $content, $matches);
if ($result === false) { die("NOT OK!"); }
echo "NUMBER OF MATCHES: ", $result, "\n";
var_dump($matches);
// THIS ALSO WORKS AS EXPECTED: matches all instances of substring '${foo}'
$result = preg_match_all('/(\$\{\w+\})/', $content, $matches);
if ($result === false) { die("NOT OK!"); }
echo "NUMBER OF MATCHES: ", $result, "\n";
var_dump($matches);
Upvotes: 2
Reputation: 43852
You need to double-escape the backslash (and you should double-escape the braces as well).
"/(\\$\\{\w+\\})/"
This is because you need to escape the backslash for the string parser, since \\
will become \
before PCRE even gets to see the string. Without the double-escape, PCRE will just get $
, which obviously will try to match the end of the string.
Upvotes: 2