下面的两种方法都起到相同的作用:扫描帖子的内容并确定是否至少有一个img标签的alt属性包含正在测试的“关键字”。使用xPath或Regex?
我是新来的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.'")]])');
}
“constains”?我认为你有一个错字。 – 2010-10-30 17:30:50
谢谢,修复了错字并编辑了xPath – 2010-10-30 17:52:47