Php 正则表达式也匹配重音字符
我有以下PHP代码:Php 正则表达式也匹配重音字符,php,regex,character,non-ascii-characters,accent-insensitive,Php,Regex,Character,Non Ascii Characters,Accent Insensitive,我有以下PHP代码: $search = "foo bar que"; $search_string = str_replace(" ", "|", $search); $text = "This is my foo text with qué and other accented characters."; $text = preg_replace("/$search_string/i", "<b>$0</b>", $text); echo $text; 我不想在
$search = "foo bar que";
$search_string = str_replace(" ", "|", $search);
$text = "This is my foo text with qué and other accented characters.";
$text = preg_replace("/$search_string/i", "<b>$0</b>", $text);
echo $text;
我不想在应用正则表达式之前替换所有重音字符,因为文本中的字符应该保持不变:
“这是我的foo文本,带有qué和其他重音字符。”
而不是
“这是我的foo文本,包含que和其他重音字符。”如果要在替换字符串中使用捕获的文本,必须在
$search
变量中使用字符类(无论如何,您可以手动设置):
依此类推。您可以尝试定义如下数组:
$vowel_replacements = array(
"e" => "eé",
// Other letters mapped to their other versions
);
foreach ($vowel_replacements as $vowel => $replacements) {
str_replace($search_string, "$vowel", "[$replacements]");
}
然后,在调用preg_match
之前,执行以下操作:
$vowel_replacements = array(
"e" => "eé",
// Other letters mapped to their other versions
);
foreach ($vowel_replacements as $vowel => $replacements) {
str_replace($search_string, "$vowel", "[$replacements]");
}
如果我没记错PHP,那么应该用重音形式的字符类来替换元音,这样可以保持元音不变。它还可以让您更轻松地更改搜索字符串;您不必记住用它们的字符类替换元音。您需要记住的是在搜索字符串中使用非重音形式
(如果有一些特殊的语法我忘记了,它没有使用foreach,请评论并让我知道。)
这和大写字母相同,将投诉您的请求。旁注:
ñ
replacemet对我来说是无效的,因为“尼诺”与“尼诺”完全不同我最后使用的解决方案:
$search_for_preg = str_ireplace(["e","a","o","i","u","n"],
["[eé]","[aá]","[oó]","[ií]","[uú]","[nñ]"],
$search_string);
$text = preg_replace("/$search_for_preg/iu", "<b>$0</b>", $text)."\n";
$search\u for\u preg=str\u ireplace([“e”、“a”、“o”、“i”、“u”、“n”],
[“[eé],[aá],[oó],[ií],[uú],[nñ],
$search_字符串);
$text=preg\u replace(“/$search\u for\u preg/iu”、“$0”、$text)。“\n”;
实际上它对我很有用。见屏幕截图:-@A-2-A不qué
不会突出显示。或者,您可以使用一些数组,例如,e
映射到eé
,并将所有出现的元音
替换为“[”$dict[$vonel]。“]”
。我在您的答案中使用stru ireplace,这正是我所需要的!该网站是为“懒惰”的人设计的,所以“n”与“ñ”匹配是正确的。)
$search_for_preg = str_ireplace(["e","a","o","i","u","n"],
["[eé]","[aá]","[oó]","[ií]","[uú]","[nñ]"],
$search_string);
$text = preg_replace("/$search_for_preg/iu", "<b>$0</b>", $text)."\n";