如何将任何给定的正则表达式"转换"为PHP`preg_match`兼容的正则表达式?

Mat*_*ens 0 php regex preg-match

好吧,这可能是一个愚蠢的问题,但我对正则表达式很新,我真的不知道如何做到这一点.

我不知道如何判断正则表达式是否适用于PHP preg_match().

例如,我想 PHP中使用以下正则表达式preg_match().

\b
# Match the leading part (proto://hostname, or just hostname)
(
    # ftp://, http://, or https:// leading part
    (ftp|https?)://[-\w]+(\.\w[-\w]*)+
  |
    # or, try to find a hostname with our more specific sub-expression
    (?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \. )+ # sub domains
    # Now ending .com, etc. For these, require lowercase
    (?-i: com\b
        | edu\b
        | biz\b
        | gov\b
        | in(?:t|fo)\b # .int or .info
        | mil\b
        | net\b
        | org\b
        | [a-z][a-z]\b # two-letter country codes
    )
)

# Allow an optional port number
( : \d+ )?

# The rest of the URL is optional, and begins with / . . . 
(
     /
     # The rest are heuristics for what seems to work well
     [^.!,?;"'<>()\[\]{}\s\x7F-\xFF]*
     (?:
        [.!,?]+  [^.!,?;"'<>()\[\]{}\s\x7F-\xFF]+
     )*
)?
Run Code Online (Sandbox Code Playgroud)

preg_match($regex, $url);当上述正则表达式按原样使用时不起作用.为什么不?在这里采取什么步骤来"转换"它以便它可以工作?

请注意,我在这里提供的正则表达式只是一个例子; 我很想学习如何将任何正则表达式转换为与其preg_match兼容的等价物.

提前致谢!

PS我问,因为我正在收集和比较这个测试页面上的不同URL正则表达式:http://mathiasbynens.be/demo/url-regex人们不断向我发送其他语言的正则表达式,我不知道如何让他们工作:(

小智 5

您可以x在PHP中使用修饰符标志以允许使用空格和注释.见http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

您还需要将正则表达式包装在一组分隔符中.所以/regex/modifiers,像这样:

/[abc]/xi
Run Code Online (Sandbox Code Playgroud)

... i修饰符用于不区分大小写.

我强烈推荐第3版Mastering Regular Expressions(第3版包含了关于PHP的整章,但整本书非常有启发性!).

PS RegexBuddy(Windows应用程序)可以为您转换语言之间的正则表达式:http://cl.ly/050z3e1Z3e050M3W2u2a 可悲的是,没有Mac版本.