2010-09-25 85 views
1
$bits = preg_split('#((?:https?|ftp)://[^\s\'"<>()]+)#S', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE); 

說,我試圖匹配需要鏈接的網址。以上是過於寬容。如何在PHP中將正則表達式與正則表達式匹配?

我想只匹配像http://google.com簡單URL,但不<a href="http://google.com">http://google.com</a>,或<iframe src="http://google.com"></iframe>

+0

你能解釋一下你正在嘗試做的,最後? – Tomalak 2010-09-25 09:36:35

+0

我試圖鏈接網址,只有在必要**時才用「 **」包裝它。 – wamp 2010-09-25 09:46:05

+0

我以爲是。這個問題在這裏被問了幾十次。請[考慮搜索](http://stackoverflow.com/search?q=),其中一個答案可能只是做你想做的。 – Tomalak 2010-09-25 10:59:26

回答

2

看來,你試圖使用正則表達式來解析HTML。 You might want to rethink that.

+0

如何在解析html的字符串中匹配url? – grapefrukt 2010-09-25 08:46:17

+3

您正在匹配HTML上下文中的網址。將HTML加載到DOMDocument中,然後根據模式測試每個文本節點。 – 2010-09-25 08:50:04

+0

我不明白這個鏈接的答案如何解決我的問題,儘管.. – wamp 2010-09-25 09:20:08

0

試試這個...

function validUrl($url){ 
     $return=FALSE; 
     $matches=FALSE; 
     $regex='#(^';     #match[1] 
     $regex.='((https?|ftps?)+://)?'; #Scheme match[2] 
     $regex.='(([0-9a-z-]+\.)+'; #Domain match[5] complete match[4] 
     $regex.='([a-z]{2,3}|aero|coop|jobs|mobi|museum|name|travel))'; #TLD match[6] 
     $regex.='(:[0-9]{1,5})?'; #Port match[7] 
     $regex.='(\/[^ ]*)?'; #Query match[8] 
     $regex.='$)#i'; 
     if(preg_match($regex,$url,$matches)){ 
      $return=$matches[0]; $domain=$matches[4]; 
      if(!gethostbyname($domain)){ 
       $return = FALSE; 
      } 
     } 
     if($return==FALSE){ 
      return FALSE; 
     } 
     else{ 
      return $matches; 
     } 
    } 
+0

我已經更新了問題以清楚說明。 – wamp 2010-09-25 08:18:59

+2

在這種情況下,更復雜的正則表達式如何提供幫助?再次閱讀問題。 – Tomalak 2010-09-25 08:21:01

+1

無論如何,試圖列舉「有效」的頂級域名是徒勞無益的。 – bobince 2010-09-25 08:55:03

0

RE

http:\/\/[a-zA-Z0-9\.\-]* 

結果

Array 
(
    [0] => http://google.com 
) 
0

更有效RE

[hf]t{1,2}p:\/\/[a-zA-Z0-9\.\-]* 

結果

Array 
(
    [0] => Array 
     (
      [0] => ftp://article-stack.com 
      [1] => http://google.com 
     ) 
)