下面的兩種方法都起到相同的作用:掃描帖子的內容並確定是否至少有一個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