【发布时间】:2011-05-02 20:50:49
【问题描述】:
下面的两种方法都有相同的目的:扫描帖子的内容并确定是否至少有一个 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.'")]])');
}
【问题讨论】:
-
“包含”?我认为你有一个错字。
-
谢谢,修正了错字并编辑了 xPath