如果元素尚未包装,如何包装?
How to wrap element if not already wrapped?
我有一组内容,其中一些 <img>
标签作为 <span class="the-image"><img src.... /></span>
包装在 span 标签内,但一些图像尚未包装。我想使用 preg_replace 创建一个正则表达式,将这个包装器添加到所有没有它的 img 标签中。
尽情享受吧!
preg_replace('/(?!\<span\sclass="the-image"\>)(<img[\sA-Z"\-_=\/.\d]*\/\>)(?!\<\/span\>)/i','<span class="the-image"\>[=10=]</span>',$code);
正则表达式示例和解释
https://regex101.com/r/cX8iL6/3
编辑
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"\>[=11=]</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 所需的答案
我有一组内容,其中一些 <img>
标签作为 <span class="the-image"><img src.... /></span>
包装在 span 标签内,但一些图像尚未包装。我想使用 preg_replace 创建一个正则表达式,将这个包装器添加到所有没有它的 img 标签中。
尽情享受吧!
preg_replace('/(?!\<span\sclass="the-image"\>)(<img[\sA-Z"\-_=\/.\d]*\/\>)(?!\<\/span\>)/i','<span class="the-image"\>[=10=]</span>',$code);
正则表达式示例和解释 https://regex101.com/r/cX8iL6/3
编辑
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"\>[=11=]</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 所需的答案