我是字符串操作新手,只是尝试替换列表中的值。
我尝试修复的两个输入是 MCAFEE
和 PORT O'BRIAN
。
所以我运行ucwords(strtolower($rawTitle))
。但现在当我需要显示 McAfee
和 Port O'Brian
时,我可以使用 Mcafee
和 Port O'brian
。
首先关注Port O'brian
,这是我的尝试,但显然它不起作用,因为它将字符串的第三个字母大写,而不是像我希望的那样将第三个匹配字符大写至:(
$oPattern = "/O\'[a-z]/"; //Pattern to match
$doesMatch = preg_match($oPattern, $output, $matches); //Do I need to the perform operation?
if ($doesMatch == 1) {
$letters = str_split($output);//break it out into an array
$cappedLetter = strtoupper($letters[2]);//capitalize the 3rd letter
$output = preg_replace("/O'$letters[2]/", $output, "O'$cappedLetter");//replace the O'x with O'X
return $output;
}
我应该在这里使用不同的函数吗?
最佳答案
不,如果字符串中没有大小写信息,则没有通用方法可以执行此操作。 (例如,考虑姓氏 O'Hara/O'hara 的两种可能的大小写。)您可以尽力尝试:
$title = ucwords(strtolower($rawTitle));
$title = preg_replace_callback('/(?<=O\'|Mc)./', function($match) {
return strtoupper($match[0]);
}, $title);
但请确保事后手动检查它们。
关于php - 如何将 "Port O' brian 替换为 "Port O' Brian”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14045450/