【发布时间】:2012-02-23 02:14:34
【问题描述】:
我需要从字符串中删除一个图像标签,同时用一些东西替换它。这是我所拥有的:
$body = '<p>Lorem ipsum dolor sit amet:</p>
<p><img class="news" id="" src="images/news_48.png" alt="" /></p>
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p>
<p><img class="gallery" id="26" src="images/gallery_48.png" alt="" /></p>
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>';
如果图像有 class="news",我需要做一件事,如果它是 class="gallery",我需要做另一件事。我在想一些伪代码,例如:
<?php
if(news){
replace the image tag where class=news with %%news%%
}
if(gallery){
replace the image tag where class=gallery with %%gallery%%
assign the value 26 to some variable
}
?>
所以现在$body 将包含:
$body = '<p>Lorem ipsum dolor sit amet:</p>
<p>%%news%%</p>
<p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ultrices sit amet:</p>
<p>%%gallery%%</p>
<p><img id="this_image_must_stay" src="images/some_image.png" alt="" /></p>';
我想我必须使用 preg_match/replace,但我不擅长正则表达式。任何帮助表示赞赏。
【问题讨论】:
-
每次在 html 上使用正则表达式时,都会有一只小猫被踩在脚下。
-
@MarkB *.com/questions/1732348/… 这是本网站上(如果不是)最受欢迎的答案之一。