php - 当 haystack 包含额外标记时,文本解析器会在 needle 上给出假阴性

标签 php regex parsing

下面的代码采用一个关键字和一串文本(经过 html 标记清理),并确定该关键字是否出现在经过清理的内容的最后一句话中。

有一个小故障我想不通。当内容末尾包含一个空格或带有不间断空格的段落标签时,即

This is the last sentence.<p>&nbsp;</p>

我得到了假阴性(不匹配),尽管事实上 (1) 关键字肯定在最后一句话中,并且 (2) strip_tags() 函数应该在最后呈现标签的外观不是问题.

有人知道为什么会这样吗?

function plugin_get_kw_last_sentence($post) {
    $theContent = strip_tags(strtolower($post->post_content));
    $theKeyword = 'test';
    $thePiecesByKeyword = plugin_get_chunk_keyword($theKeyword,$theContent);
    if (count($thePiecesByKeyword)>0) {
        $theCount = $thePiecesByKeyword[count($thePiecesByKeyword)-1];
        $theCount = trim($theCount,'.');
        if (substr_count($theCount,'.')>0) {
            return FALSE;
        } else {
            return TRUE;
        }
    }
    return FALSE;
}

function plugin_get_chunk_keyword($theKeyword, $theContent) {
    if (!plugin_get_kw_in_content($theKeyword,$theContent)) {
        return array();
    }

    $myPieceReturn = preg_split('/\b' . $theKeyword . '\b/i', $theContent);
    return $myPieceReturn;
}

最佳答案

如果我正确理解您的逻辑,我认为可以仅在正则表达式中涵盖您那里发生的很多事情。整个逻辑不能简化为:

function plugin_get_kw_last_sentence($post) {
    $pattern = '/' . $theKeyword . '[^.!?]*[.!?][^.!?]*$/';
    $subject = strip_tags(strtolower($post->post_content));
    return preg_match($pattern, $subject);
}

正则表达式在找到您的关键字和最后一个句子结尾标点符号且它们之间没有其他句子结尾标点符号时匹配。

现在这显然不是防弹的,因为诸如头衔(即先生、夫人)等...以及包括这些句末标点符号在内的任何其他内容都会让您失望。这应该可以满足您的要求,因为您给定的代码也没有考虑到这些情况。

关于php - 当 haystack 包含额外标记时,文本解析器会在 needle 上给出假阴性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5799263/

相关文章:

用于 trac 样式格式的 php wiki 解析器

Javascript 获取两个日期之间的时差

php - Ajax 登录和 javascript cookie,这安全吗?

php - 在 Weight WooCommerce 之前添加文本

regex - vim:将包含模式的行移动到上一行的末尾

python - 将一个字典中的值与另一个字典中的键链接起来,并使用正则表达式在字符串中将一个替换为另一个

php - mysql 查询的多个循环

PHP 查询以从 friend 和自己检索文本和/或图像状态更新

python - 类型错误 : expected string or buffer

Java解析带有问号标签的XML?