2017-01-03 54 views
1

我一直在嘗試識別網頁的網址格式。對於我跟着以下,但已經結束了一個問題PHP的正則表達式來識別特定的網址格式

- 使用> PHP正則表達式:

~((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)~i 

這已經確定了幾乎所有類型的URL像下面

example.com 
www.example.com 
http://example.com 
http://www.example.com  
https://example.com 
https://www.example.com 

但不幸的是它也考慮十進制值,價格值,電話號碼,IP地址作爲URL格式(可能我以前沒有考慮過它們)。因此,要解決這個問題我已經使用以下來找到特定的數字值的模式要被排除

/^[0-9]+(\.[0-9]{1,})+\S+\w?$/ 

使用這已通過排除像

Deciaml值(1.11)

數值固定的URL標識符IP地址(123.123.123.123)

價格值($ 11.11)

現在到了新問題「的縮寫,也考慮ED作爲網址」

W.H.O(在任何情況下,按字母順序排列)

所以,我怎麼能有一個URL識別PHP正則表達式將不包括上述問題的情況?

我能有一個PHP的正則表達式來識別涉及像上面的例子縮寫字母單值?

感謝

+0

你不應該發佈鏈接到僞造的URL。這是代碼,所以你必須格式化它(這是工具欄按鈕): –

+0

請原諒我的錯別字:) –

+0

嘗試[''〜\ b(?![AZ](?:\。[AZ]) (?:\ \ d +)| + \ b \ d +?+ \ S + \ b)(?(HTTPS://)([ - \ W] + \ [ - \ W] +)+ \ W( ?:: \ d +)(/([ - \ W/_。] *(:???\ \ S +))?)*)\ b〜''](https://regex101.com/r/ iuozYk/2) –

回答

0

你可以把這些排除爲負向前查找和使用

$re = '~(?x)\b     # Word boundary 
    (?!       # Exclusion list 
    [A-Z](?:\.[A-Z])+\b   # No upper and 1+ sequences of . + an upper 
    |       # or 
    \d+(?:\.\d+)+\S+\b   # digits + 1+ dot and digits and 1+ non-whitespaces 
    )  
    (?:https?://)?    # Optional http/https protocol part 
    (?:[-\w]+\.[-\w.]+)+   # 1+ sequences of 1+ - or word chars, then . and 1+ -, ., or word chars 
    \w(?::\d+)?     # word char and 1 optional sequence of : and 1+ digits 
    (?:/(?:[-\w/.]*(?:\?\S+)?)?)* # 0+ sequences of /, 0+ -, word, /, . symbols, then 1 optional sequence of ? and 1+ non-whitespaces 
    \b~';       # word boundary 
$str = 'example.com www.example.com http://example.com http://www.example.com  https://example.com https://www.example.com Deciaml Values (1.11) IP Address (123.123.123.123) W.H.O Price values ($11.11)'; 
preg_match_all($re, $str, $matches); 
print_r($matches[0]); 

PHP demo在線和regex demo here

+1

它的工作原理!非常感謝@WiktorStribiżew –