Preg_match在特定的img-tag中查找img src

时间:2014-04-10 13:30:24

标签: php html

我有一行源代码看起来像这样

 <img alt="this field is variable" title="this one too" itemprop="photo" border="0" style="width:608px;" src="imgurl.jpg">

网站上有很多其他图片,所以我不能只是preg_match所有图片,我需要特定的图像,我在做特定的preg_match时遇到了很多麻烦,因为&的内容#34; alt&#34; -tag和&#34; title&#34; -tag是可变的。谁知道怎么做?提前谢谢。

Itemprop =&#34;相片&#34;这张照片是独一无二的。

2 个答案:

答案 0 :(得分:3)

这个正则表达式应该有效:

preg_match('/<img[^>]*itemprop="photo"[^>]*src="([^"]+)">/',$source,$matches);

正则表达式的解释(来自regex101):

Explanation of the regex

结果将在数组$matches中。

答案 1 :(得分:0)

Using regex to parse HTML is not a good thing。为什么不使用DOMDocument来搜索您的元素? PHP具有这些对象,用于通过HTML文档进行解析,并且比使用正则表达式尝试查找元素更容易。然后,您还可以更轻松地操作HTML,具体取决于您要完成的操作。

$dom = new DOMDocument();
$dom->loadHTML(<your html string>);

$imgs = $dom->getElementsByTagName('img');
$photos = [];
foreach($imgs as $img) {
      if($img->attributes->getNamedItem('itemprop') && $img->attributes->getNamedItem('itemprop')->nodeValue = 'photo') {
         $photos[] = $img->attributes->getNamedItem('src')->nodeValue;
     }
}

此代码将为您提供一个数组,其中包含具有您的属性的imgs的src属性,并且您不依赖于如何创建元素或html的实际文本中的任何内容。

相关问题