PHP:正则表达式匹配字符串前面没有美元符号
在我的语法荧光笔中,我使用正则表达式来解析不同的术语。下面是我解析 PHP 类的方法:
foreach ( PHP::$Classes as $class )
$code = preg_replace( "/\b{$class}\b/", $this->_getHtmlCode( $class, PHP::$Colors['class'] ), $code );
现在,忽略 PHP 类和 _getHtmlCode 函数。正则表达式 "/\b{$class}\b/"
匹配 count
等名称。如果我创建一个名为 $count
的变量,它会很好地匹配。
如何查找前面没有 $
的类名?
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 $
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用负零宽度后视来完成相同的任务 - 基本上,以确保文本之前没有美元符号:
/(?。
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}/
.你想匹配 className 吗?即
class className {}
或$foo = new className
如果是这样,您可以检查类名之前是否有一个或多个空格:
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:
奇怪的是 $ 算作边界不是吗?
无论如何,一个解决方法是将其放在 \b 之后:
请参阅 http:// /www.php.net/manual/en/regexp.reference.assertions.php 的含义
以下是演示这一点的测试脚本:
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: