[英]RegEx UTF-8 ignore and bold special characters
我的网站搜索框具有以下代码:
<? echo preg_replace("/({$term})/i", "<b>$0</b>", NoticiaInfo($news_results, 'subtitulo')); ?>
而且我想知道是否有任何方法可以使字母“ c”用正则表达式代替“ç”。
因此,如果我搜索“ ca”,则“Função”的字母“çã”将被加粗...
有没有办法用正则表达式来做到这一点?
您需要将preg_replace与数组配合使用。 尝试:
<?php
$replacements = array(
'/a/' => '<b>ã</b>',
'/c/' => '<b>ç</b>'
);
echo preg_replace(array_keys($replacements), array_values($replacements), NoticiaInfo($news_results, 'subtitulo'));
?>
并用您要$replacements
的其他字符填充$replacements
数组。
@Ranty很好,因此您可以尝试使用str_replace,您的代码将变为:
<?php
$replacements = array(
'a' => '<b>ã</b>',
'c' => '<b>ç</b>'
);
echo str_replace(array_keys($replacements), array_values($replacements), NoticiaInfo($news_results, 'subtitulo'));
?>
没有做到这一点并保留口音标记的漂亮方法。 首先,您必须用替换的字符组合搜索词的所有可能排列的列表。
<?
$termList = array($term);
// You'll need to programmatically create this list
// This is just a sample, assuming that $term == 'Funcao';
$termList[] = 'Funcão';
$termList[] = 'Funçao';
$termList[] = 'Função';
$bodyText = NoticiaInfo($news_results, 'subtitulo');
foreach($termList as $searchTerm) {
$bodyText = preg_replace("/({$searchTerm})/i", "<b>$0</b>", $bodyText);
}
echo $bodyText;
?>
以编程方式创建搜索词数组将是一场噩梦,但是已经有许多密码破解应用程序已经做到了(例如:它们为数字细分字符并创建其每个排列),因此逻辑存在于某个地方。 但是,当您开始使用更长的搜索字符串时,其开销开始变得一发不可收拾。
当然,如果您不关心保持重音符号,这将变得更加容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.