简体   繁体   English

preg_match() 不匹配 img src

[英]preg_match() not matching img src

I have this string in a php variable.我在 php 变量中有这个字符串。

$str = 'This is an iamge: <img src="images/Christmas.PNG" width=70%; height=40%">';

The pattern I am searching:我正在搜索的模式:

$pattern = '/<img src="(.*?)>/g';

I then have this preg_match()然后我有这个preg_match()

preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);

When i go to print $matches either directly by echo $matches or in a foreach loop, the variable is null.当我 go 直接通过echo $matches或在 foreach 循环中打印$matches时,变量为 null。

Why is this happening?为什么会这样? Thanks.谢谢。

Don't use regexes for parsing HTML . 不要使用正则表达式来解析 HTML There are tools designed for this very thing.有专门为此而设计的工具。

You can use DOMDocument to parse the HTML and then easily get the value of the src attribute:您可以使用DOMDocument解析 HTML ,然后轻松获取src属性的值:

$previous_value = libxml_use_internal_errors(true);
$string = 'This is an iamge: <img src="images/Christmas.PNG" width=70%; height=40%">';
$dom = new DOMDocument();
$dom->loadHTML($string);
echo $dom->getElementsByTagName('img')->item(0)->getAttribute("src");
libxml_clear_errors();
libxml_use_internal_errors($previous_value);

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM