2010-11-16 20 views
0

我有這個網址...無法添加http:// mainserver/all(href | action | src)=,讓我陷入困境!

$output = "href=\"/one/two/three\" 
href=\"one/two/three\" 
src=\"windows.jpg\" 
action=\"http://www.google.com/docs\""; 

當我申請正則表達式:

$base_url_page = "http://mainserver/"; 
$output = preg_replace("/(href|src|action)(\s*)=(\s*)(\"|\')(\/+|\/*)(.*)(\"|\')/ismU", "$1=\"" . $base_url_page . "$6\"", $output); 

我得到這個:

$output = "href=\"http://mainserver/one/two/three\" 
href=\"http://mainserver/one/two/three\" 
src=\"http://mainserver/windows.jpg\" 
action=\"http://mainserver/http://www.google.com/docs\""; 

如何修改正則表達式,以防止這個:http://mainserver/http://www.google.com/ ???????

+3

在HTML與正則表達式解析幾點建議:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2010-11-16 02:18:22

+0

將它只需使用['BASE'元素](http://www.w3.org/TR/html4/struct/links.html#edef-BASE)更改基本URI即可? – Gumbo 2010-11-16 17:18:03

回答

1

嘗試

$output = preg_replace("/(href|src|action)\s*=\s*["'](?!http)\/*([^"']*)["']/ismU", "$1=\"" . $base_url_page . "$2\"", $output); 

我已經簡化您的正則表達式,並增加了一個前瞻,使得確保你匹配的字符串不以http啓動。就像現在一樣,這個正則表達式不允許在URL內使用單引號或雙引號。

+0

這將不允許包含簡單''''''''('*是一個有效的URI!')的屬性值。 – Gumbo 2010-11-16 17:20:34

+0

我知道,這就是爲什麼我在我的答案中這樣寫的。如果這是OP的問題,則可以更改正則表達式。 – 2010-11-16 20:09:25

+0

這個解決方案非常好,謝謝...只有當href =「/ url」...我們纔會得到結果:href = http:// mainserver // url ---> // (在我的正則表達式中,我使用:(\/+ | \/*))解決了這個問題...... – 2010-11-17 04:16:04

0
$output = preg_replace("/(href|src|action)\s*=\s*[\"'](?!http)(\/+|\/*)([^\"']*)[\"']/ismU", "$1=\"" . $base_url_page . "$3\"", $output); 
相關問題