PHP: Regex match string not preceeded by a dollar sign
In my syntax highlighter, I use regex to parse different terms. Below is how I parse PHP cla开发者_开发知识库sses:
foreach ( PHP::$Classes as $class )
$code = preg_replace( "/\b{$class}\b/", $this->_getHtmlCode( $class, PHP::$Colors['class'] ), $code );
Now, just ignore the PHP class and the _getHtmlCode function. The regex, "/\b{$class}\b/"
, matches names such as count
. If I make a variable named $count
, it matches that was well.
How can I look for class names that are not preceded by a $
?
You could use a negative zero-width look-behind to accomplish the same task - basically, to make sure that there isn't a dollar sign before your text: /(?<!\$){$class}/
.
(?<! # Non-capturing look-behind group, captures only if the following regex is NOT found before the text.
\$) # Escaped dollar sign
{$class} # Class name
Are you trying to match className? i.e. class className {}
or $foo = new className
If so you could check for one or more spaces before the classname:
/[ ]+{$class}\b/
Curious that $ counts as a boundary isn't it. Anyway, one fix is to put this after the \b:
(?<!\$)
See http://www.php.net/manual/en/regexp.reference.assertions.php for what it means
Here was the test script that demonstrates this:
$list=array(
'class MyClass',
'class HisClass',
'var $MyClass',
);
foreach($list as $s){
echo $s."\n";
if(preg_match('/\bMyClass\b/',$s))echo "OK";else echo "Failed";
echo "\n";
if(preg_match('/\b(?<!\$)MyClass\b/',$s))echo "OK";else echo "Failed";
echo "\n";
}
精彩评论