如何在突出显示关键字的函数中支持引号


How to support quotes in a function that highlights keywords

我有这个函数突出显示关键字。它工作得很好,但似乎不适合单引号和双引号。

function highlight($input, $keywords) {
    // Hello Mr Regex
    preg_match_all('~'w+~', $keywords, $match);
    // If there's no match
    if(!$match) { return $input; }
    // Case sensitive search
    //$result = '~''b(' . implode('|', $match[0]) . ')''b~';
    // Case insenstive search
    $result = '~''b(' . implode('|', $match[0]) . ')''b~i';
    // Return highlighted text
    return preg_replace($result, '<strong>$0</strong>', $input);
}

$keywords = "just another what's little's test";

$input = "here what what's just looking little's another's this's for another one that requires a test";


Result: here what what's just looking little's another's this s for 另一个需要测试


在这个例子中,它不应该在上突出显示


我也尝试使用htmlspecialchars()的输入和关键字,但这似乎也没有得到匹配。

任何想法?

'w只能是字母、数字和下划线。如果你想包含引号或撇号,你可以创建一个字符类:

preg_match_all('~['w''"]+~' ...