我需要从字符串中删除图像标记,同时将其替换为某些内容。这就是我所拥有的:
$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,但我不擅长正则表达式。任何帮助表示赞赏。
答案 0 :(得分:0)
<?php
$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>';
if (preg_match('{.*<img class="gallery".*}', $body)) {
$some_variable = 26;
}
print preg_replace('{<img class="(news|gallery)".*/>}', '%%\\1%%', $body);
?>
答案 1 :(得分:0)
谢谢,我最终得到了这个。它有点工作:)
<?php
$str = preg_replace('/<img class="news"[^>]+\>/i', "%%news%%", $str);
preg_match('/<img class="gallery" id="(.*?)"[^>]+\>/i', $str, $id);
$id = $id[1];
$str = preg_replace('/<img class="gallery"[^>]+\>/i', "%%gallery%%", $str);
echo $str;
?>
但后来我想到了,如果我有两个或更多画廊图片并且想要获取他们的ID那会怎么样。 %% gallery %%必须以某种方式链接到每个%% gallery %%的相应ID。