我想将一个点后或点和空格后的首字母大写。
$string="I am a string with several periods.period #1. period #2.";
这应该是最后一个字符串:
I am a string with several periods.Period #1. Period #2.
我已经在寻找关于stackoverflow的解决方案,但是我发现的解决方案仅是将一个点后的首字母大写而不是一个点和一个空格。
答案 0 :(得分:1)
使用正则表达式匹配点\.
,可选空格\s*
和字母\w
。
然后循环匹配数组并执行str_replace。
$str="I am a string with several periods.period #1. period #2.";
preg_match_all("/\.\s*\w/", $str, $matches);
foreach($matches[0] as $match){
$str = str_replace($match, strtoupper($match), $str);
}
echo $str;
//I am a string with several periods.Period #1. Period #2.
为使其更加优化,您可以在循环之前添加array_unique,因为str_replace会替换所有相等的子字符串。
$matches[0] = array_unique($matches[0]);
答案 1 :(得分:1)
Preg_replace_callback是你的朋友:
$string="I am a string with several periods.period #1. period #2.";
$string = preg_replace_callback('/\.\s*\K\w/',
function($m) {
return strtoupper($m[0]);
},
$string);
echo $string;
输出:
I am a string with several periods.Period #1. Period #2.
答案 2 :(得分:0)
如果不能使用正则表达式,则可能会执行以下操作:
$str = "I am a string with several periods.period #1. period #2.";
$strings = explode('.', $str);
$titleCased = [];
foreach($strings as $s){
$titleCased[] = ucfirst(trim($s));
}
echo join(".", $titleCased);
尽管如此,它还具有消除空白的作用。
答案 3 :(得分:0)
我创建了这个简单的函数,它就像一个魅力
,您可以根据需要添加定界符。
function capitalize_after_delimiters($string='', $delimiters = array())
{
foreach ($delimiters as $delimiter)
{
$temp = explode($delimiter, $string);
array_walk($temp, function (&$value) { $value = ucfirst($value); });
$string = implode($temp, $delimiter);
}
return $string;
}
$string ="I am a string with several periods.period #1. period #2.";
$result = capitalize_after_delimiters($string, array('.', '. '));
var_dump($result);
result: string(56) "I am a string with several periods.Period #1. Period #2."