【问题标题】:PHP - remove <img> tag from stringPHP - 从字符串中删除 <img> 标签
【发布时间】:2010-11-09 13:58:17
【问题描述】:

嘿,我需要从字符串中删除所有图像,但我找不到正确的方法。

这是我尝试过的,但它不起作用:

preg_replace("/<img[^>]+\>/i", "(image) ", $content);
echo $content;

有什么想法吗?

【问题讨论】:

  • $content = preg_replace(..., $content);
  • 你可以使用txt2re.com来制定正则表达式。通常,我使用这个,然后根据我的需要修改代码。

标签: php string


【解决方案1】:

尝试将\ 放在&gt; 前面。

编辑:我刚刚测试了你的正则表达式,它工作正常。这是我用的:

<?
    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); 
    echo $content;
?>

结果是:

这是带有(图像)的东西。

【讨论】:

  • 除了 (image) 之外,你能把它替换成图片的 alt 吗?
  • 尝试将 \ 放在 > 前面。 preg_replace("/&lt;img[^&gt;]+\&gt;/i", "(image) ", $content);这与实际问题有什么不同?
【解决方案2】:

我建议使用strip_tags 方法。

【讨论】:

  • 这会去除所有标签,而不仅仅是img标签。
【解决方案3】:

您需要将结果分配回$content,因为preg_replace 不会修改原始字符串。

$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);

【讨论】:

    【解决方案4】:

    Sean 运行良好,我刚刚使用了这段代码

    $content = preg_replace("/<img[^>]+\>/i", " ", $content); 
    echo $content;
    

    //结果它只是纯文本。好用!!!

    【讨论】:

      【解决方案5】:

      我想将新闻报道的前 300 个单词显示为预览,这不幸的是,如果故事在前 300 个单词中有图像,那么它会显示在预览列表中,这确实与我的布局相混淆。我使用上面的代码隐藏了从我的数据库中获取的字符串中的所有图像,它的效果非常好!

      $news = $row_latest_news ['content'];
      $news = preg_replace("/<img[^>]+\>/i", "", $news); 
      if (strlen($news) > 300){
      echo substr($news, 0, strpos($news,' ',300)).'...';
      } 
      else { 
      echo $news; 
      }
      

      【讨论】:

      • 评论使用 mini-Markdown 格式:link italic bold code。帖子作者将始终收到您的评论通知。要通知之前的评论者,请提及他们的用户名:
      【解决方案6】:
      $this->load->helper('security');
      $h=mysql_real_escape_string(strip_image_tags($comment));
      

      如果用户输入

      在数据库表中只需插入字符#

      为我工作

      【讨论】:

        【解决方案7】:

        只需使用codeigniter的form_validation类:

        strip_image_tags($str).
        
        $this->load->library('form_validation');
        $this->form_validation->set_rules('nombre_campo', 'label', 'strip_image_tags');
        

        【讨论】:

        • 他说他在用 CodeIgniter 吗?
        猜你喜欢
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        • 2014-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多