Php 从字符串中删除图像标记并替换为字符串

Php 从字符串中删除图像标记并替换为字符串,php,string,replace,match,Php,String,Replace,Match,可能重复: 我需要从字符串中删除一个图像标记,同时用其他内容替换它。以下是我所拥有的: 我想我必须使用preg_match/replace,但我不擅长正则表达式。非常感谢您的帮助。您可以这样做: $body = '<p>Lorem ipsum dolor sit amet:</p> <p>%%news%%</p> <p>Curabitur tincidunt vehicula mauris, nec facilisis nisl ul

可能重复:

我需要从字符串中删除一个图像标记,同时用其他内容替换它。以下是我所拥有的:


我想我必须使用preg_match/replace,但我不擅长正则表达式。非常感谢您的帮助。

您可以这样做:

$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>';

谢谢,我最终得到了这个。这类作品:)



但后来我想,如果我有两个或更多的画廊图片,并想获取他们的身份证呢。对于每个%%gallery%%,必须以某种方式将%%gallery%%链接到其各自的id

每次在html上使用正则表达式时,都会有一只小猫被踩死。@MarkB这是本网站上最流行的答案之一(如果不是的话)。或者:
<?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 = '<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>';
<?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);

?>
<?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;
?>