3

I am trying to parse php variables in a string using regex. For instance,

$str = '$str1var ="str1"; $str2var = "str2"';

would give me an array ['str1var', 'str2var']

My regex pattern in php is: "/\$(.*?)=/s"

$pattern = "/\$(.*?)=/s";
preg_match_all($pattern, $str, $output_array);

but preg_match_all is returning 0 (no matches) What is wrong with my regex? I tested on a site like http://www.phpliveregex.com/ and it works fine, but my server returns 0;

My Server PHP version is 5.1.6

1
  • is it returning 0 or false? var_dump should tell you... the regex should work tohugh, although the output should be more like ['str1var ', 'str2var ']
    – Rooster
    Jan 8, 2014 at 21:23

3 Answers 3

3

PHP seems to have problem with the double quotes surrounding your pattern, perhaps it is looking for a variable because of the $ sign.

Your code does not work in any php version, but with single quotes it works in all php versions, see the example:

$pattern = '/\$(.*?)=/s';
3
  • This fixed it. Thanks. I also just realized (based on the answer from @JakeGould ) that modifying my pattern to "/\\$(.*?)=/s" also works. Jan 8, 2014 at 21:33
  • @StephaniAlves var_dump($pattern); -> $(.*?)=/s and you see, if the $ is escaped for regex. It must be escaped for the regex-engine, as it's a metacharacter and you want to match the literal.
    – Jonny 5
    Jan 8, 2014 at 21:37
  • @StephaniAlves: Be carefull, the number of backslashes you need to obtain a literal backslash in a simple string (not a regex pattern) is not the same if you use single or double quotes. So, if you want to obtain an escaped $ in a pattern with single quotes, you only need one backslash. If you want to do the same with double quotes, you must put two backslashes (note that if you put three backslashes, the third is ignored). Jan 8, 2014 at 21:53
1

Variables are parsed within double quotes in PHP.

0
 $pattern = '/\$(?P<variable>.*?)(?:\s|)=(?:\s|)"(?P<value>.*?)"/';

Returns an associative array with the value if you need it.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.