2010-02-15 31 views
2

我正在學習正則表達式。我有一個很簡單的問題:將url路徑中的lang更改爲子域的正則表達式

我的php.I內容的一長串想所有的地方轉換,它說:

http://www.example.com/en/rest-of-url 

http://en.example.com/rest-of-url 

有人能幫助我和這個?我想我使用preg_replace這個?

獎勵:如果你有一個好網站的鏈接,它解釋瞭如何在正則表達式中這樣做最簡單的事情,請張貼它。我所看到的每個正則表達式資源都非常快速(甚至維基百科文章)。

回答

3

在PHP:

$search = '~http://www.example.com/([^/]+)/(.+)~'; 
$replace = 'http://$1.example.com/$2'; 
$new = preg_replace($search, $replace, $original); 
2

假設:

preg_replace($regex, $replaceWith, $subject); 

$ subject爲原文。 $正則表達式應該是:

'@http://([^\.]*)\.example\.com/en/(.*)@' 

$ replaceWith應該是:

'http://$1.example.com/$2' 

EDITED:在我orignial的答案,我已經錯過了,你想捕捉域名的一部分的事實。

+0

您應該使用不同的字符作爲分隔符而不是'/',它使正則表達式更易於理解。 – DisgruntledGoat

2

這將與任何域名工作:

$url = 'http://www.example.com/en/rest-of-url'; 

echo preg_replace('%www(\..*?/)(\w+)/%', '\2\1', $url); 

給出:

http://en.example.com/rest-of-url 

參考:preg_replace

2

您可以瞭解關於B asic正則表達式,但是對於你的簡單問題,沒有必要使用正則表達式。

$str="http://www.example.com/en/rest-of-url"; 
$s = explode("/",$str); 
unset($s[3]); 
print_r(implode("/",$s)) ;