Skip to content
Advertisement

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 classes:

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 $?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement