2016-08-12 18 views
0

我嘗試更換以下標記及其內容與空字符串:優化正則表達式:重複出現次數

<a href="http://localhost/photo/448e7d40ed468d73c5f9caba573f6273-0.png" class="wall-image-anchor" target="_blank"><img src="http://localhost/photo/448e7d40ed468d73c5f9caba573f6273-0.png" /></a> 

注意裏面<a>標籤href網址可以是任何東西。所以<a>內部的內容,在這種情況下<img>及其內容。

到目前爲止,我得到了下面的代碼:

$text = preg_replace('@(.*?)<(?:a\b.*?class="wall-image-anchor".*?)>.*?</a>(.*?)@si', '$1$2', $text); 

此代碼應變換以下字符串:

zzzzz<a href="http://localhost/zz/photo/448e7d40ed468d73c5f9caba573f6273-0.png " class="wall-image-anchor" target="_blank"><img src="http://localhost/zz/photo/448e7d40ed468d73c5f9caba573f6273-0.png" alt="Image/photo" /></a>ffff<br /><a href="http://localhost/ada/photo/448e7d40ed468d73c5f9caba573f6273-0.png " class="wall-image-anchor" target="_blank"><img src="http://localhost/ada/photo/448e7d40ed468d73c5f9caba573f6273-0.png" alt="Image/photo" /></a>ffffgg ffff<br /><a href="http://localhost/dad/photo/448e7d40ed468d73c5f9caba573f6273-0.png " class="wall-image-anchor" target="_blank"><img src="http://localhost/dad/photo/448e7d40ed468d73c5f9caba573f6273-0.png" alt="Image/photo" /></a>ffffgg' 

到:

zzzzzffff 
ffffgg ffff 
ffffgg 

此代碼的工作。我的問題是:有沒有其他辦法可以讓它更快?

問候

+0

也許'回聲用strip_tags(str_replace函數( ''(你的「進入」示例沒有這些)。 'echo strip_tags($ string,'
');' – chris85

回答

1

這裏的第一個問題是正確性。正如所寫,您的正則表達式將從第一個<a>標記的開始處開始匹配,而不管其屬性是什麼。 (demo)您需要將內部.*? s替換爲超出標籤邊界的東西,即[>]*

這也將大大減少回溯量,大大提高性能。你應該做的另一件事是擺脫(.*?)任何一端。任何與正則表達式不匹配的東西都不會受替換操作的影響,所以你只是讓它做不必要的工作。

下面是它應該是什麼樣子:

'@<a\b[^>]*class="wall-image-anchor"[^>]*>.*?</a>@si' 

demo

+0

太棒了!非常感謝 – ethereal1m

0

你知道比賽是如何工作的懶惰,所以你怎麼不只是做到這一點?

$var = "zzzzz<a href=\"http://localhost/zz/photo/448e7d40ed468d73c5f9caba573f6273-0.png \" class=\"wall-image-anchor\" target=\"_blank\"><img src=\"http://localhost/zz/photo/448e7d40ed468d73c5f9caba573f6273-0.png\" alt=\"Image/photo\" /></a>ffff<br /><a href=\"http://localhost/ada/photo/448e7d40ed468d73c5f9caba573f6273-0.png \" class=\"wall-image-anchor\" target=\"_blank\"><img src=\"http://localhost/ada/photo/448e7d40ed468d73c5f9caba573f6273-0.png\" alt=\"Image/photo\" /></a>ffffgg ffff<br /><a href=\"http://localhost/dad/photo/448e7d40ed468d73c5f9caba573f6273-0.png \" class=\"wall-image-anchor\" target=\"_blank\"><img src=\"http://localhost/dad/photo/448e7d40ed468d73c5f9caba573f6273-0.png\" alt=\"Image/photo\" /></a>ffffgg'"; 

$output = preg_replace("/<.*?>/", "", $var); 

或者你只是想特別匹配一個href和img嗎?

PS。下次請隔開您的字符串,以便更容易地查看您想要捕捉的部分。

+0

是的,我需要檢測特定的類。這是由Alan – ethereal1m