【问题标题】:Remove img in html that non contain src attribute删除 html 中不包含 src 属性的 img
【发布时间】:2015-07-16 22:48:42
【问题描述】:

我需要使用 preg_match 和 PHP 删除 html 中所有不包含 src 属性的 img 元素

类似:

<html>
 <img src="someurl" alt="something"  />
 <img  alt="something"  />
<html />

<html>
 <img src="someurl" alt="something"  />
<html />

坦克

【问题讨论】:

标签: php html regex dom preg-replace


【解决方案1】:

如果你的老板坚持使用正则表达式,并且(s)他没有听到智慧的声音,你可以尝试以下正则表达式:

(?si)\s*<img\b(?>(?!src=).)*?\/>\s*

demo on regex101

示例 PHP 代码:

$re = "/(?si)\\s*<img\\b(?>(?!src=).)*?\\/>\\s*/"; 
$str = "<html>\n <img src=\"someurl\" alt=\"something\"  />\n <img  alt=\"something\"  />\n <img  alt=\"somethingelse\"\n       att='val'  />\n<html />"; 
$result = preg_replace($re, "", $str);

【讨论】:

    猜你喜欢
    • 2012-05-12
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多