【发布时间】:2011-11-26 08:49:28
【问题描述】:
对于我的自动建议功能,我需要为建议中的摘录着色......所以......
如果我搜索类似 “萨” 建议者给了我以下内容
三星 讽刺 数据 e-sata ...
现在我想从我的函数中突出显示 - 将“sa”针(所有出现)包裹在所需的 html 标记中。
喜欢 萨msung sa轮胎 sata e-sata
- 应该是 utf8 安全的
- 它应该保留大写
- 它应该忽略 HTML
在 PHP 网站上,我找到了一个可以替换并保持大写的函数...我对其进行了修改,使其对 utf8 友好...
function ext_str_ireplace($findme, $replacewith, $text) {
// Replaces $findme in $subject with $replacewith
// Ignores the case and do keep the original capitalization by using $1 in $replacewith
// Required: PHP 5
$rest = $text;
$result = '';
while (mb_stripos($rest, $findme) !== false) {
$pos = mb_stripos($rest, $findme);
// Remove the wanted string from $rest and append it to $result
$result .= mb_substr($rest, 0, $pos);
$rest = mb_substr($rest, $pos, mb_strlen($rest)-$pos);
// Remove the wanted string from $rest and place it correctly into $result
$result .= mb_ereg_replace('$1', mb_substr($rest, 0, mb_strlen($findme)), $replacewith);
$rest = mb_substr($rest, mb_strlen($findme), mb_strlen($rest)-mb_strlen($findme));
}
// After the last match, append the rest
$result .= $rest;
return $result;
}
效果很好……喜欢
ext_str_ireplace("sa", "<b>sa</b>", "Samsung");
直到我将一些 html 代码传递给它
$text= '<p class="red">A client is an application or system that accesses a service made available by a server. </p>';
ext_str_ireplace("cl", "<b>cl</b>", $text);
该函数当然会替换 "cl" 字符串
【问题讨论】:
-
谢谢马里奥....我使用了下面答案中的解决方案,并从您的链接中添加了一些内容........+ 我添加了 utf8 标志,以确保安全..... return preg_replace('/('.$expression.')(?=[^>]*($1', $text);