好的,這可能是一個愚蠢的問題,但我對正則表達式很新,而且我真的不知道如何做到這一點。如何將任何給定的正則表達式轉換爲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人們不斷給我的正則表達式中的其他語言,我不知道如何使他們的工作:(
您必須先將所有的空格和註釋去掉,我不認爲有任何簡單的自動化方法;空格是PHP正則表達式中的空白字符。您不能簡單地刪除所有空白,因爲其中一些可能很重要。 – meagar 2010-12-03 21:14:40
@meager:PHP支持自由間隔模式,與Perl相同;將``〜`加到開頭,`〜x'加到最後,這個正則表達式在PHP中工作正常。 – 2010-12-05 22:04:22