2014-01-29 107 views
0
if(preg_match(/(www|co.uk|uk.com|com|net|edu|org|org.uk|info|me|biz|co|io)/, $hostParts)) { 

    //unset this element from the array; 

} 

我正在使用正則表達式來刪除常見的域擴展。我擁有的問題是我的表達式也與www.cnet.com示例中的cnet中的網絡匹配。我怎樣才能阻止它匹配例如www.cnet.com這樣的域名部分,因爲我只想刪除www和com部分。謝謝。停止正則表達式匹配單詞中某個單詞的部分

回答

2

一般來說,\b做你想要的很大一部分。用兩個\b s入站你的話。 but check the updates for your specific case

if(preg_match('/\b(www|co.uk|uk.com|com|net|edu|org|org.uk|info|me|biz|co|io)\b/si', $hostParts)) { 

    //unset this element from the array; 

} 

UPDATE

這是一個更新,這是具體的網址,我並沒有考慮到這一點:

if(preg_match('/(\bwww\.|(\.(co\.uk|uk\.com|com|net|edu|org|org.uk|info|me|biz|co|io)\b))/si', $hostParts)) { 

    //unset this element from the array; 

} 

更新2

這裏是一個例子,請注意,我已將「org」與「org.uk」交換,因爲如果第一個被抓到第二個將不會︰

<?php 

    $str = 'www.cnet.org.uk'; 
    $str = preg_replace('/(\bwww\.|(\.(co\.uk|uk\.com|com|net|edu|org.uk|org|info|me|biz|co|io)\b))/si', '', $str); 
    echo $str; 

?> 
+0

謝謝你這正是我所需要的。我是新來的正則表達式,只是得到它們的竅門。 –

+0

請查看最後一個例子。它有一些交換。 –

相關問題