下面的两种方法都有相同的目的:扫描帖子的内容并确定是否至少有一个 img 标签具有包含正在测试的“关键字”的 alt 属性。
我是 xPath 的新手,并且更愿意使用它,具体取决于该方法与正则表达式版本相比的昂贵程度...
方法 #1 使用 preg_match
function image_alt_text_has_keyword($post)
{
$theKeyword = trim(wpe_getKeyword($post));
$theContent = $post->post_content;
$myArrayVar = array();
preg_match_all('/<img\s[^>]*alt=\"([^\"]*)\"[^>]*>/siU',$theContent,$myArrayVar);
foreach ($myArrayVar[1] as $theValue)
{
if (keyword_in_content($theKeyword,$theValue)) return true;
}
return false;
}
function keyword_in_content($theKeyword, $theContent)
{
return preg_match('/\b' . $theKeyword . '\b/i', $theContent);
}
方法 #2 使用 xPath
function keyword_in_img_alt()
{
global $post;
$keyword = trim(strtolower(wpe_getKeyword($post)));
$dom = new DOMDocument;
$dom->loadHTML(strtolower($post->post_content));
$xPath = new DOMXPath($dom);
return $xPath->evaluate('count(//a[.//img[contains(@alt, "'.$keyword.'")]])');
}
最佳答案
如果您正在解析 XML,您应该使用 XPath,因为它正是为此目的而设计的。 XML/XHTML 不是正则语言,不能被正则表达式正确解析。您也许可以编写一个在某些时候有效的正则表达式,但在特殊情况下它会失败。
关于regex - 使用 xPath 还是正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4059812/