这个问题在这里已经有答案了:

有没有一个实用程序可以将 PHP 的 POSIX 转换为 PCRE?我对 PCRE 上的 PHP 手册有些困惑,虽然我会尝试查找有关 PCRE 的更多信息,但我想知道是否有人设计了这样的实用程序。

或者,如果有人能解释如何转换以下内容,那也很好:

ereg("^#[01-9A-F]{6}$", $sColor)

但请解释一下它是如何完成的,而不仅仅是告诉我转换。

有帮助吗?

解决方案

preg_match("/^#[01-9A-F]{6}$/", $sColor)
In this case you only need to add the two delimiters.

在 Perl 中你可以写类似的东西

if ( s =~ /x.+y/ )
{ print "match"; }
As you can see the actual regular expression is encapsulated in //. If you want to set an option on the regular expression you put it after the second /, e.g. switching the expression to ungreedy by default /x.+y/U
pcre now emulates this behaviour. Though you have to call a function you also have to provide the delimiters and set the options after the second delimiter. In perl the delimiter has to be /, with pcre you can chose more freely
preg_match("/^#[01-9A-F]{6}$/", $sColor)
preg_match("!^#[01-9A-F]{6}$!", $sColor)
preg_match("#^\#[01-9A-F]{6}$#", $sColor) // need to escape the # within the expression here
preg_match("^#[01-9A-F]{6}$", $sColor)
与 PCRE 一样,最好选择表达式中没有出现的字符。

其他提示

preg_match("/^#[01-9A-F]{6}$/D", $sColor)

请注意 D 修饰语. 。人们总是忘记它。没有它 $ 将允许最后一个换行符。像“#000000 ”这样的字符串将会通过。这是 POSIX 和 PCRE 之间的细微差别。

而且当然, [01-9] 可以重写为 [0-9].

顺便说一下,PHP 同时支持 PCRE 和 POSIX 正则表达式。这是 PHP 手册中有关 POSIX 正则表达式的部分,因此您不必转换它们: http://www.php.net/manual/en/book.regex.php

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top