php - 使用 RegEx 进行多词搜索和匹配

标签 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

最佳答案

描述

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

\b(这个需要|这里|可以高亮文字)\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>

关于php - 使用 RegEx 进行多词搜索和匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16800966/

相关文章:

名称中带有点的php对象属性

java - 匹配星号但不匹配星号

asp.net - "Characters Numbers"的正则表达式

python - 简单的函数调用在 Robot Framework 中不起作用

php - 获取其他数组值对应的多维数组索引值

php - 如何计算相关表中的行数

javascript - 拉维尔 4 : Sidebar is not clickable

c# - 如何从路径中获取文件名?

swift - 如何从另一个 Controller 快速调用函数

Java - 将参数设置为既扩展一个对象又实现一个接口(interface)的对象