PHP:正则表达式匹配字符串前面没有美元符号

发布于 2024-11-24 09:55:28 字数 401 浏览 2 评论 0原文

在我的语法荧光笔中,我使用正则表达式来解析不同的术语。下面是我解析 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

只是在用心讲痛 2024-12-01 09:55:28

您可以使用负零宽度后视来完成相同的任务 - 基本上,以确保文本之前没有美元符号:/(?。

(?<!     # Non-capturing look-behind group, captures only if the following regex is NOT found before the text.
  \$)    # Escaped dollar sign
{$class} # Class name

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
白云不回头 2024-12-01 09:55:28

你想匹配 className 吗?即 class className {}$foo = new className

如果是这样,您可以检查类名之前是否有一个或多个空格:

/[ ]+{$class}\b/

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/
情栀口红 2024-12-01 09:55:28

奇怪的是 $ 算作边界不是吗?
无论如何,一个解决方法是将其放在 \b 之后:

(?<!\$)

请参阅 http:// /www.php.net/manual/en/regexp.reference.assertions.php 的含义

以下是演示这一点的测试脚本:

$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";
    }

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";
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文