PHP:从页面上回显的内容中剥离图像标记

时间:2013-06-25 11:33:02

标签: php

我正在从数据库中删除一些内容,其中一些内容可能包含图像,但我只需要提取文本内容而不回显内容中可能包含的任何图像。

示例:

   $nws = '<h3>Just text Just text Just text Just text Just text Just text.</h3>

    <p><img alt="" src="/opt_file/images/09062013C-pix1.jpg" style="width: 400px; height: 231px;" /></p>

<img alt="" src="/opt_file/images/another-pix2.png" style="width: 300px; height: 150px;" />

    <p>Just text Just text Just text Just text Just text Just text.</p>

    <p>Just text Just text Just text Just text Just text Just text.</p>

    <p><strong>Sure these are just text.</strong></p>';

    $nws = str_replace( '<img alt="" src="" />', "" , $nws );

    echo $nws;

我尝试使用str_replace来删除任何图像标记或图像,但它无法正常工作。

此外,这些内容和图片都是动态的,特定的可能会有多个图片。

真的需要解决这个问题,非常感谢获得帮助。

谢谢!

2 个答案:

答案 0 :(得分:1)

使用正则表达式,

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

答案 1 :(得分:1)

使用strip_tags()功能,例如:

$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);

要删除特定的html标记,请使用此功能:

echo strip_tags($text,'<p>');