2013-10-30 25 views
3

我有各种格式的网址输入。我想将全部转换成一种标准格式。下面是几个示例输入。preg_replace如果不存在特定模式

从所有的输入的上方,我希望与WWW转换成第一个(http://www.example.com)。所以我认为如果“www”不在那里,我们可以替换字符串。

$pattern = '/((http?|https)\:\/\/)?([a-zA-Z]+)\.example.com\/[a-z]{2}\/[a-zA-Z0-9]{5,30}/i'; 

我试过这种模式。我知道它会匹配取代一切。所以请建议我,如何做到这一点。

回答

1
function to_standard_format($url) { 
    $pattern = '#(https?://)?\w+\.example.com(?=[/\s]|$)#i'; 
    return preg_replace($pattern, 'http://www.example.com', $url); 
} 

var_dump(to_standard_format('http://www.example.com')); 
var_dump(to_standard_format('https://in.example.com')); 
var_dump(to_standard_format('http://uk.example.com')); 
var_dump(to_standard_format('http://uk.example.com/blah')); 
var_dump(to_standard_format('uk.example.com')); 
var_dump(to_standard_format('http://www.example.com.au')); 
var_dump(to_standard_format('uk.another-example.com')); 

打印

string(22) "http://www.example.com" 
string(22) "http://www.example.com" 
string(22) "http://www.example.com" 
string(27) "http://www.example.com/blah" 
string(22) "http://www.example.com" 
string(25) "http://www.example.com.au" 
string(22) "uk.another-example.com" 
+0

example.com会像example1.com每次变化,所以我不能代替它的完整路径,只有我想取代英国。或等到www。 – Gowri

+0

@gowri,我几分钟前稍微更新了答案。已更新的答案使用肯定的前瞻断言,并且不会更改完整路径。 – falsetru

0

,据我了解,你只需要替换为 “”(空字符串)第一部分。所以你需要像https?://(www。)这样的模式?

即的preg_replace( “HTTPS:??//(WWW)”, “http://www.example.com”, “”)