2016-02-28 53 views
1

我有一組內容,其中一些<img>標籤被封裝在span標籤內,如<span class="the-image"><img src.... /></span>,但某些圖像尚未包裝。我想用preg_replace創建一個正則表達式來將這個包裝添加到所有那些沒有它的img標籤。如何包裝元素,如果尚未包裝?

回答

1

享受!

preg_replace('/(?!\<span\sclass="the-image"\>)(<img[\sA-Z"\-_=\/.\d]*\/\>)(?!\<\/span\>)/i','<span class="the-image"\>$0</span>',$code); 

Regex的實施例說明& https://regex101.com/r/cX8iL6/3

EDIT

PHP的preg_replace例如

$code = <<< EOT 
<span class="the-image"><img src="123" /></span><br /> 
<img src="1234" /><br /> 
<span class="the-image"><img src="blah/blah/blah" /></span> 
EOT; 

$code = preg_replace('/(?!\<span\sclass="the-image"\>)(<img[\sA-Z"\-_=\/.\d]*\/\>)(?!\<\/span\>)/i','<span class="the-image"\>$0</span>',$code); 

/* $code will become this 

<span class="the-image"><img src="123" /></span><br /> 
<span class="the-image"><img src="1234" /></span><br /> 
<span class="the-image"><img src="blah/blah/blah" /></span> 

*/ 

編輯2更改正則表達式來和PHP,以反映所需的OP ANSW呃

+0

你確定嗎?你仍然有第二張圖像的開放跨度。 – aslamdoctor

+0

是的,這將使它所以 '' 將成爲 '' –

+0

鏈接沒有做替換,它只是顯示瞭如何將正則表達式匹配 –