2010-12-03 83 views
0

好的,這可能是一個愚蠢的問題,但我對正則表達式很新,而且我真的不知道如何做到這一點。如何將任何給定的正則表達式轉換爲PHP preg_match兼容的正則表達式?

我不知道如何判斷一個正則表達式是否適用於PHP的preg_match()

例如,我想使用the following regex和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]+ 
    )* 
)? 

preg_match($regex, $url);當使用上述正則表達式原樣不工作。爲什麼不? 有什麼步驟來「轉換」它,以便它能夠工作?

請注意,我在這裏提供的正則表達式只是一個示例;我很想學習如何將任何正則表達式轉換爲與preg_match兼容的等效表達式。

提前致謝!

P.S.我問,因爲我收集這個測試頁上比較不同的URL的正則表達式:http://mathiasbynens.be/demo/url-regex人們不斷給我的正則表達式中的其他語言,我不知道如何使他們的工作:(

+0

您必須先將所有的空格和註釋去掉,我不認爲有任何簡單的自動化方法;空格是PHP正則表達式中的空白字符。您不能簡單地刪除所有空白,因爲其中一些可能很重要。 – meagar 2010-12-03 21:14:40

+1

@meager:PHP支持自由間隔模式,與Perl相同;將``〜`加到開頭,`〜x'加到最後,這個正則表達式在PHP中工作正常。 – 2010-12-05 22:04:22

回答

5

您可以使用在PHP中x修改標誌,允許使用空格和評論見http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php

而且你需要用正則表達式中的一組delimiters所以/regex/modifiers,就像這樣:。

/[abc]/xi 

...的i米大小寫不區分大小寫。

我強烈推薦掌握正則表達式的第3版(第3版包括關於PHP的整章,但整本書很有啓發性!)。

P.S. RegexBuddy(Windows應用程序)可以爲您在各種語言之間轉換正則表達式:http://cl.ly/050z3e1Z3e050M3W2u2a可悲的是,沒有Mac版本。

0

請原諒我去題外話,但正則表達式並不包括所有TLD的。例如。它缺少.museum和.aero

關於添加新頂級域名(TLD)或者甚至允許任何東西作爲頂級域名(TLD)的問題,我建議不要使用枚舉它們的正則表達式。