【问题标题】:remove image tag from string and replace with string [duplicate]从字符串中删除图像标签并用字符串替换[重复]
【发布时间】:2012-02-23 02:14:34
【问题描述】:

可能重复:
PHP - remove <img> tag from string

我需要从字符串中删除一个图像标签,同时用一些东西替换它。这是我所拥有的:

$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,但我不擅长正则表达式。任何帮助表示赞赏。

【问题讨论】:

标签: php string replace match


【解决方案1】:

你可以这样做:

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

?>

【讨论】:

    【解决方案2】:

    谢谢,我终于搞定了。它有点工作:)

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

    【讨论】:

      最近更新 更多