2013-10-30 30 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」, 「」)