从字符串中删除非<img>标签

问题描述 投票:0回答:5
php html regex sanitization strip-tags
5个回答
9
投票

你不应该在 HTML 上使用正则表达式,那这个呢:?

$string = '<span class="introduction"><img alt="image" src="/picture.jpg" /></span>';

echo strip_tags($string, '<img>');

否则我会使用 HTML/XML 解析器


6
投票

怎么样

"<img[^>]*>"

尝试使用 grep

kent$  echo '<span class="introduction">
quote>    <img alt="image" src="/picture.jpg" />
quote> </span>
quote> '|grep -P "<img[^>]*>"
   <img alt="image" src="/picture.jpg" />

5
投票

preg_match('#(<img.*?>)#', $string, $results);

应该有效,结果是

$results[1]


1
投票

使用 DOM 和此 XPath:

//span[@class="introduction"]/img

查找所有具有类属性introduction的span元素的直接子元素img元素。


1
投票

我已经找到了这个解决方案

/<img ([^>"']*("[^"]*"|'[^']*')?[^>"']*)*>/

测试于

<other html elements like span or whatever><img src="asd>qwe" attr1='asd>qwe' attr2='as"dqwe' attr3="as'dqwe" ></other html elements like span or whatever>

© www.soinside.com 2019 - 2024. All rights reserved.