View Full Version : regexp strangely not working

Phil Jackson
10-22-2009, 08:02 PM
Hi all i have this:

$line = ' $lineTest = trim($line);';
$line = preg_replace("#(\s*)(\$(?:@?|\!|_)?[a-z]+(?:[a-z]|[0-9]|_)*)(\s+)#is", "\\1<span class=\"variable\">\\2</span>\\3", $line);

[0] => $lineTest
[1] =>
[2] => $lineTest
[3] =>

using a regexp tool the output i receive indicates it works.. but it doesn't
Trying to get variables.

10-25-2009, 11:44 PM
First of all, I'd recommend looking at token_get_all - it tokenizes php scripts for you, so you won't accidentally match variable names in '' quotes or other invalid places.


As for your example, it's often best to use regex quoted with apostrophes ', not quotes " to save you having to "double-slash".

Correct: '#(\s*)(\$(?:@?|\!|_)?[a-z]+(?:[a-z]|[0-9]|_)*)(\s+)#is'
Or: "#(\\s*)(\\$(?:@?|\\!|_)?[a-z]+(?:[a-z]|[0-9]|_)*)(\\s+)#is"

Also, are your \s necessary? This won't match "Hi ".$name."!", for example.