I need remove all img element in html that non contain src attribute with preg_match and PHP
我需要使用preg_match和PHP删除不包含src属性的html中的所有img元素
something like:
<html>
<img src="someurl" alt="something" />
<img alt="something" />
<html />
in
<html>
<img src="someurl" alt="something" />
<html />
Tanks
1 个解决方案
#1
In case your boss insists on a regex, and (s)he does not hear to the voice of wisdom, you can try the following regex:
如果你的老板坚持正则表达式,并且(s)他没有听到智慧的声音,你可以尝试以下正则表达式:
(?si)\s*<img\b(?>(?!src=).)*?\/>\s*
See demo on regex101.
请参阅regex101上的演示。
Sample PHP code:
示例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);
#1
In case your boss insists on a regex, and (s)he does not hear to the voice of wisdom, you can try the following regex:
如果你的老板坚持正则表达式,并且(s)他没有听到智慧的声音,你可以尝试以下正则表达式:
(?si)\s*<img\b(?>(?!src=).)*?\/>\s*
See demo on regex101.
请参阅regex101上的演示。
Sample PHP code:
示例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);