2010-07-16 84 views
0

我一直在努力與此一段時間,所以希望有人可以幫助我。例如,我需要使用正則表達式替換錨標記內的所有空格。替換裏面的所有空間<a>標籤

Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all 

需求,成爲

Hello this is a string, check this <a[SPACE]href="http://www.google.com">Google[SPACE]is[SPACE]cool</a> Oh and this <a[SPACE]href="http://www.google.com/blah[SPACE]blah">Google[SPACE]is[SPACE]cool</a> That is all 
+0

我不知道如何做到這一點,因爲我正則表達式避免像瘟疫。與其給你一個真正的答案,我寧願建議你使用PHP的內置函數str_replace()。 http://php.net/str_replace - 雖然也許你的情況是這樣的,你需要使用正則表達式,我沒有理由這樣做。 – Teekin 2010-07-16 13:17:51

回答

1

我們正在處理的正則表達式和XMLish串 - 儘管對於給定的測試用例以下工作,你可能里程爲不同的測試情況有所不同;仔細使用。

<? 
function replace($matches) 
{ 
     return preg_replace("/ /", "[SPACE]", $matches[0]); 
} 
$s = 'Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all'; 
echo "Before::......\n\n$s\n\nAfter::......\n\n"; 
echo preg_replace_callback('#<a\b(.+?)</a>#', 'replace', $s); 
echo "\n"; 
?> 

輸出

Before::...... 

Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all 

After::...... 

Hello this is a string, check this <a[SPACE]href="http://www.google.com">Google[SPACE]is[SPACE]cool</a> Oh and this <a[SPACE]href="http://www.google.com/blah[SPACE]blah">Google[SPACE]is[SPACE]cool</a> That is all 
0
preg_replace(
    '/(<a .+?<\/a>)/e', 
    'str_replace(" ", "[SPACE]", "\1")', 
    'Hello this is a string, check this <a href="http://www.google.com">Google is cool</a> Oh and this <a href="http://www.google.com/blah blah">Google is cool</a> That is all' 
);