搜索结果的 str_ireplace 区分大小写替换

Case (in)sensitive Replace for str_ireplace for search results

我有一个物品清单。我想在搜索词中使用它们。假设列表是:

现在,如果我正在搜索关键字 world(注意所有字母都是小写字母),我将提供此功能。

preg_replace(/world/, '<span class="label label-search-results">[=11=]</span>', $item);

其中$item是每一行,输出是:

Warning: preg_replace() [function.preg-replace]: Delimiter must not be alphanumeric or backslash in /myfile.php on line XX.

如果我使用str_ireplace(),我不知道找到的文本的原始大小写。它会是这样的:

str_ireplace("world", '<span class="label label-search-results">world</span>', $item);

这导致所有 worldWorldWORLD 均为小写。关于替换后如何保留 案例有什么想法吗?

preg_replace('/(world)/i', '<span class="label label-search-results"></span>', $item);

尝试使用标志 i 来区分大小写。

这是 preg_replace_callback() 的完美用例,只需像这样使用它:

echo preg_replace_callback("/" . preg_quote($_GET["q"], "/")  . "/i", function($m){
    return "<span class='label label-search-results'>" . $m[0] . "</span>";
}, $item);