简体   繁体   English

PHP preg_replace()大写和小写区别

[英]PHP preg_replace() upper and lowercase difference

I have a PHP/Ajax search function that returns all countries which hold the characters entered in a textbox. 我有一个PHP / Ajax搜索功能,它返回所有保存在文本框中输入字符的国家。 All these countries are listed and the given characters are marked bold inside the country it's name in the list. 所有这些国家均已列出,并且给定字符在列表中其名称所在的国家/地区内以粗体标记。

Example Characters given in textbox: "Af" Which return Af ghanistan and South Af rica - without the space inbetween ofcourse 在文本框定的例子人物:“AF”这回房颤 ghanistan和南方房颤哥斯达黎加-无其间ofcourse空间

Now all the countries names in the database ofcourse start with a uppercase letter. 现在,课程数据库中的所有国家/地区名称都以大写字母开头。 But

preg_replace() preg_replace()

can not find the difference between Upper and lowercase letters. 找不到大写和小写字母之间的区别。 So when i enter "a" in the textbox it will return Afgh a nist a n notice the first uppercase "A" not made bold 因此,当我输入“A”在文本框中它会返回一个 Afgh NIST 首先注意到的大写字母“A”没有作出大胆

Here is the code i am using 这是我正在使用的代码

$display_name = preg_replace("/" . $search_string . "/", "<b>" . $search_string . "</b>", $result['Country_Name']);
$display_url = '';

$output = str_replace('NameReplace', $display_name, $HTML);
$output = str_replace('UrlReplace', $display_url, $output);
echo($output);

I can "fix" this problem adding the "/i" modifier to the preg_replace() According to PHP.net it will do the following: 我可以“解决”此问题,将“ / i”修饰符添加到preg_replace()根据PHP.net,它将执行以下操作:

i (PCRE_CASELESS) If this modifier is set, letters in the pattern match both upper and lower case letters. i(PCRE_CASELESS)如果设置了此修饰符,则模式中的字母将同时匹配大写和小写字母。

This will turn the bold characters inside the countries name lowercase or uppercase according to the characters inside the textbox 这将根据文本框内的字符将国家名称内的粗体字符变为小写或大写

example: Characters given in textbox: "A" will return " A fgh A nist A n" while "a" will return " a fgh a nist a n" again please ignore the white space. 例如:在给定的文本字符: “A”将返回“A FGH 一个 NIST A N”,而“一”将返回“ 一个 FGH 一个 NIST ”再次请忽略的空白。

How can i make it that when i enter: "a" it will return " A fgh a nist a n" ? 我怎样才能使它的是,当我输入:“A”则返回“A FGH 一个 NIST ”?

Thank you 谢谢

Change this: 更改此:

$display_name = preg_replace("/" . $search_string . "/", "<b>" . $search_string . "</b>", $result['Country_Name']);

to this: 对此:

$display_name = preg_replace("/(" . $search_string . ")/i", '<b>$1</b>', $result['Country_Name']);

Try this: 尝试这个:

echo preg_replace("/a/i", "<b>\1</b>", "Afghanistan");

Outputs in HTML : HTML输出

A fgh a nist a n 一个 FGH 一个 NIST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM