使用preg_replace从字符串中删除'img'标记

时间:2012-07-16 11:04:56

标签: php regex preg-replace

  

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

我的内容是这样的:

$content = '<p>&nbsp;</p>
<p><img width="645" height="450" src="/proshore/userfiles/image/1.jpg" alt="" /></p>
<p>An explorer adventures into an unknown world, yet it seems that he has been there      before. A short animated film directed by Malcolm Sutherland in 2010. With music by Alison Melville and Ben Grossman, and foley by Leon Lo. Sound design / mix by Malcolm Sutherland.</p>
<p>The animation is all hand-drawn; a mix of drawing / pastels on paper and digital animation with Toonboom Studio and a wacom cintiq tablet, assembled in After Effects 7 and edited in Sony Vegas 8.</p>
<p>&nbsp;</p>';

我希望输出忽略<img>标记。我尝试了preg_replace的一些混乱,但没有用。如果有人能解释我的工作方式,这将是一个很好的帮助。

3 个答案:

答案 0 :(得分:1)

如果您没有被迫use regular expressions to parse HTML content,那么我建议使用PHP的strip_tags()函数及其allowed_tags参数。

这将告诉PHP删除所有html标记,并将指定的标记保留在allowed_tags中。

the documentation -

中使用的示例
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text); 
// output : Test paragraph. Other text

// Allow <p> and <a>
echo strip_tags($text, '<p><a>'); 
// output - <p>Test paragraph.</p> <a href="#fragment">Other text</a>

因此,如果您只是在allow_tags 中指定除<img>标记之外的所有HTML标记,则应获得所需的结果 - 仅删除{{1来自你的字符串的标签。

答案 1 :(得分:0)

尝试:

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

答案 2 :(得分:0)

将此正则表达式<img.+?((/>)|(</img>))替换为空字符串