【问题标题】:Preg_match to find img src in specific img-tagPreg_match 在特定的 img-tag 中查找 img src
【发布时间】:2014-04-10 13:30:23
【问题描述】:

我有一行像这样的源代码

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

网站上有很多其他图片,所以我不能只对所有图片进行 preg_match,我需要特定的图片,我在进行特定 preg_match 时遇到了很多麻烦,因为“alt”标签和“标题“-标签是可变的。有人知道该怎么做吗?提前致谢。

Itemprop="photo" 是这张照片的独特之处。

【问题讨论】:

  • 很明显,如果您不告诉我们如何区分 this img 标签和 others,我们将无能为力!
  • 这些标签如何脱颖而出,是什么让它们与众不同?如果他们不这样做,有没有办法让他们?你有能力为他们添加一些东西吗?
  • 你可以做 something like this 但将类更改为 itemprop 否则 this is quite helpful for explaining regexes
  • 是的,很抱歉我的描述不好。 itemprop="photo" 是将它们与文件中的其他图像分开的那个。不幸的是,我没有能力添加任何东西。

标签: php html


【解决方案1】:

这个正则表达式应该可以工作:

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

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

结果将在数组$matches中。

【讨论】:

  • 感谢您的解释,它几乎可以工作,但必须在开头和结尾添加“/”分隔符才能使其正常工作,但很好的答案!赞赏
  • 好的,我会把它添加到我的答案中。
【解决方案2】:

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 的实际文本中的任何内容。

【讨论】:

  • 一般来说,你不应该使用正则表达式来解析 HTML(你不能),但是如果你有一个明确定义的模式,regex can be the tool of choice
猜你喜欢
  • 2012-02-10
  • 2021-04-05
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
相关资源
最近更新 更多