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

标签 php regex preg-replace

Possible Duplicate:
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 尝试了一些困惑,但没有成功。如果有人能向我解释它是如何工作的,这将是一个很大的帮助。

最佳答案

如果你不是被迫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 中的所有 HTML 标记除了<img>标签,您应该得到您需要的结果 - 只需删除 <img>字符串中的标签。

关于php - 使用 preg_replace 从字符串中删除 'img' 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11502977/

相关文章:

php - 合并或组合两个数组 - 仅当指定的 id 存在时

php - 我如何重写这段代码以提高其清晰度?

php - 使用 preg_replace 时如何增加替换字符串中的计数?

php - 使用 preg_replace 替换单引号之间的所有点字符

php - 输出 array_count_values 提取键和值

php - mootools单选按钮问题

python - Pandas : Count the number of occurrence of all matched patterns in a column

带有正则表达式的 Javascript 选择器

java - 正则表达式 (Java) 异常 - 寻求解释

php - 制作一行正则表达式