使用xPath还是Regex?

Sco*_*t B 5 regex xpath

下面的两个方法各自用于相同的目的:扫描帖子的内容并确定至少一个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);
        }
Run Code Online (Sandbox Code Playgroud)

方法#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.'")]])');
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 14

如果要解析XML,则应使用XPath,因为它是为此目的而设计的.XML/XHTML不是常规语言,无法通过正则表达式正确解析.您可能能够编写一个在某些时候有效的正则表达式,但会出现失败的特殊情况.

  • "XPath用于浏览XML文档中的元素和属性." 从马口(W3C). (3认同)
  • http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 (2认同)