使用RegEx进行多字搜索和匹配

时间:2013-05-28 20:32:12

标签: php regex function

我创建了一个突出字符串中单个单词的函数。它看起来像这样:

function highlight($input, $keywords) {

    preg_match_all('~[\w\'"-]+~', $keywords, $match);

    if(!$match) { return $input; }

    $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i';

    return preg_replace($result, '<strong>$0</strong>', $input);

}

我需要使用该函数来处理支持搜索空间的不同单词数组。

示例:

$search = array("this needs", "here", "can high-light the text");

$string = "This needs to be in here so that the search variable can high-light the text";

echo highlight($string, $search);

以下是我到目前为止修改函数以满足我的需要:

function highlight($input, $keywords) {

    foreach($keywords as $keyword) {

        preg_match_all('~[\w\'"-]+~', $keyword, $match);

        if(!$match) { return $input; }

        $result = '~\\b(' . implode('|', $match[0]) . ')\\b~i';

        $output .= preg_replace($result, '<strong>$0</strong>', $keyword);

    }

    return $output;

}

显然这不起作用,我不知道如何让它发挥作用(正则表达不是我的强项)。

另一点可能是问题,该函数将如何处理多重匹配?例如$search = array("in here", "here so");,结果就像是:

This needs to be <strong>in <strong>here</strong> so</strong> that the search variable can high-light the text

但这必须是:

This needs to be <strong>in here so</strong> that the search variable can high-light the text

1 个答案:

答案 0 :(得分:3)

描述

您可以使用您的术语数组并使用正则表达式或语句|将它们连接起来然后将它们嵌套到字符串中。 \b将有助于确保您不会捕获单词片段。

\b(this needs|here|can high-light the text)\b

enter image description here

然后使用捕获组\1

将其作为替代品运行

实施例

我并不熟悉Python,但在PHP中我会做这样的事情:

<?php
$sourcestring="This needs to be in here so that the search variable can high-light the text";
echo preg_replace('/\b(this needs|here|can high-light the text)\b/i','<strong>\1</strong>',$sourcestring);
?>

$sourcestring after replacement:
<strong>This needs</strong> to be in <strong>here</strong> so that the search variable <strong>can high-light the text</strong>