2014-01-29 180 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

请查看最后一个例子。它有一些交换。 –

相关问题