php - 如何将 "Port O' brian 替换为 "Port O' Brian”?

标签 php regex string

我是字符串操作新手,只是尝试替换列表中的值。

我尝试修复的两个输入是 MCAFEEPORT O'BRIAN

所以我运行ucwords(strtolower($rawTitle))。但现在当我需要显示 McAfeePort O'Brian 时,我可以使用 McafeePort 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/

相关文章:

php - 如何检查数据库中已有的空表

php - 在 PHP 中读取原始 I/O 流的替代方法

php - 特定行上的自举表 ionic

string - UTF-16 编码 - 为什么使用复杂的代理对?

string - 如何获取 TStringList 中的最后一个字符串

php - 需要一些 PHP 逻辑来遍历一些 mysql 数据库结果

c++ - 无法编译(未声明且预期的主表达式)

javascript正则表达式在匹配模式后获取字符串

regex - 如何使用正则表达式进入postgresql第n个定界符左侧或右侧的子字符串

string - 替换字符串中第一次出现的模式