使用 # 作为分隔符的 preg 正则表达式中的注释?

Comments in preg regexes using # as delimiter?

使用类似 perl 的正则表达式语法,您可以使用 /x 修饰符和 # 字符对注释进行 内联注释 ,但是如果我使用 PHP 并出于样式原因使用 # 作为分隔符,那么有什么方法可以发表评论吗?

preg_replace("/foo # This is a comment\n/x", "bar","foobar")

有效但

preg_replace("#foo # This is a comment\n#x", "bar","foobar")

不起作用,///**/ 或我尝试过的任何常见注释序列也不起作用。

在 PHP 正则表达式模式中,定界符比模式部分多 "weight"。如果将定界符定义为 #,则不能将其用作另一个特殊结构的一部分。因此,"#foo # This is a comment\n#x""#foo (?# This is a comment\n)#x" 将不起作用,因为 # 表示正则表达式中模式 space 的结束。

当您对 # 进行转义时,它会变成文字 # 符号。 "#foo \# This is a comment\n#x" 将匹配 "foo#Thisisacomment",因为一旦转义,它就会作为文字符号匹配。

所以,最好的建议可以在 "Delimiters" page at php.net:

If the delimiter needs to be matched inside the pattern it must be escaped using a backslash. If the delimiter appears often inside the pattern, it is a good idea to choose another delimiter in order to increase readability.