将文本动态插入字符串(PHP)


Dynamically Inserting Text Into String (PHP)

我有一个PHP脚本,它根据网站搜索框中的术语在数据库中运行搜索。这将返回一个文本块。假设我现在的搜索词是"test block"。我的结果的一个例子是这个文本块:

这是使用搜索查询。

现在,我的问题是:如何在文本块中"突出显示"搜索词,以便用户能够首先看到为什么会出现此结果。使用上面的例子,类似以下内容就足够了:

这是从数据库收集的文本测试块来自搜索查询。

到目前为止,我已经尝试了一些可以改变文本的方法,但我遇到的真正问题与区分大小写有关。例如,如果我使用代码:

$exploded = explode(' ', $search_terms);
foreach($exploded as $word) {
    // I have to use str_ireplace so the word is actually found
    $result = str_ireplace($word, '<b>' . $word . '</b>', $result);
}

它会通过我的$resultbold的任何单词实例。这看起来是正确的,正如我在搜索结果的第二个示例中所希望的那样。但是,在用户使用"Test Block"而不是"test block"的情况下,搜索项将被大写并显示为:

这是从数据库收集的文本的测试块来自搜索查询。

这对我来说不起作用,尤其是当用户使用小写搜索词时,它们恰好落在sentance的开头。

从本质上讲,我需要做的是在字符串中找到单词,将文本(本例中为<b>(直接插入单词前面,然后将文本直接插入单词后面(本例为</b>(,同时保持单词本身不被替换。我相信这将preg_replacestr_replace排除在外,所以我真的陷入了该做什么的困境

任何线索都将不胜感激。

$exploded = explode(' ', $search_terms);
foreach($exploded as $word) {
    // I have to use str_ireplace so the word is actually found
    $result = preg_replace("/(".preg_quote($word).")/i", "<b>$1</b>", $result);
}

图案匹配http://www.php.net/manual/en/reference.pcre.pattern.syntax.php使用某些字符,如。[]/*+等。因此,如果这些出现在模式中,则需要首先使用pre_quote(); 进行转义

模式以分隔符开始和结束,以识别模式http://www.php.net/manual/en/regexp.reference.delimiters.php

遵循我的修饰符http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php在这种情况下,i表示不区分大小写的

(括号(中的任何内容都会被捕获以供以后使用,无论是在$matching参数中,还是在替换中,第一个为$1或''''1,第二个为$2等。

使用preg_replace。在您的示例中

$result = preg_replace("/''b(" . preg_quote($word) . ")''b/i", '<b>$1</b>', $result);

您可以使用preg_replace:

foreach ($exploded as $word) {
    $text = preg_replace("`(" . preg_quote($word) . ")`Ui" , "<b>$1</b>" , $text);
}
$string = 'The quick brown fox jumped over the lazy dog.';
$search = "brown";
$pattern = "/".$search."/";
$replacement = "<strong>".$search."</strong>";
echo preg_replace($pattern, $replacement, $string);

快速的brown狐狸跳过懒狗