我將此代碼用于 reg ex 以獲取具有類“wp-post-image”的每個 img 元素,但它正在獲取沒有該標簽的影像,只是因為它們在附近:
$results = 'img src="https://api.follow.it" border=0 width="1" height="1"> <img width="150" height="150" src="https://www.sitefeed.com/testImage.jpg" class="webfeedsFeaturedVisual wp-post-image"<p>This is a test for RSS feeds</p>';
$pattern = '/<img. ?class=".*?wp-post-image.*?"/';
preg_match($pattern, $results, $classMatches);
dump($classMatches);
使用該 HTML 片段,我在轉儲中獲取了兩個影像元素。
如何僅將影像與匹配的類名匹配?
uj5u.com熱心網友回復:
您可以使用以下功能:
function get_string_between(string $str, string $tagName, string $findClass = '')
{
$tags = explode('<', $str);
$classMatches = '';
foreach ($tags as $tag) {
if (strpos($tag, $tagName) !== false && strpos($tag, $findClass) !== false ) {
$tag = str_replace('>', '', $tag);
$classMatches .= '<' . $tag . '>';
}
}
return $classMatches;
}
$classMatches = get_string_between($results, 'img', 'wp-post-image');
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454710.html
上一篇:我如何在PHP中運行函式exec
