[英]Preg_match to find img src in specific img-tag
我有一行看起來像這樣的源代碼
<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”標簽和“ title”的內容標簽是可變的。 有人知道怎么做嗎? 提前致謝。
Itemprop =“ photo”是此圖片唯一的東西。
這個正則表達式應該工作:
preg_match('/<img[^>]*itemprop="photo"[^>]*src="([^"]+)">/',$source,$matches);
正則表達式的解釋(來自regex101 ):
結果將在數組$matches
。
使用正則表達式解析HTML不是一件好事 。 為什么不使用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;
}
}
此代碼將讓你用的src屬性的陣列imgs
有你的財產,你是不依賴於如何創建或HTML的實際文本的任何元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.