我有一个函数,它假设使所有句子的第一个字符大写,但由于某种原因,它没有对第一个句子的第一个字符这样做。为什么会发生这种情况,我该如何解决?
<?php
function ucAll($str) {
$str = preg_replace_callback('/([.!?])'s*('w)/',
create_function('$matches', 'return strtoupper($matches[0]);'), $str);
return $str;
} //end of function ucAll($str)
$str = ucAll("first.second.third");
echo $str;
?>
结果:
first.Second.Third
预期成果:
First.Second.Third
它不大写第一个单词,因为正则表达式要求在它前面有.
、!
或?
之一。第一个单词前面没有这些字符之一。
这将做到这一点:
function ucAll($str) {
return preg_replace_callback('/(?<=^|['.'?!])[^'.]/', function ($match) {
return strtoupper($match[0]);
}, $str);
}
它使用正向后看来确保.
、!
、?
或行首之一位于匹配字符串的前面。
试试这个
function ucAll($str) {
$str = preg_replace_callback('/([.!?])'s*('w)|^('w)/',
create_function('$matches', 'return strtoupper($matches[0]);'), $str);
return $str;
} //end of function ucAll($str)
$str = ucAll("first.second.third");
echo $str;
|^('w)
是"或获取第一个字符"
像这样
: function ucAll($str) {
$result = preg_replace_callback('/([.!?])'s*('w)/',function($matches) {
return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($str)));
return $result;
} //end of function ucAll($str)
$str = ucAll("first.second.third");
echo $str;
输出:
第一。第二。第三
发生这种情况
是因为您的正则表达式仅匹配您定义的标点符号集之后的字符,并且第一个单词不遵循其中一个。我建议进行以下更改:
首先,此组([?!.]|^)
匹配字符串的开头 ( ^
) 以及您要尝试替换的(可选)空格和单词字符之前的标点符号列表。以这种方式设置它意味着如果字符串开头有任何空格,它应该仍然有效。
其次,如果您使用的是 PHP>= 5.3,建议使用匿名函数而不是create_function
,希望此时是这样(如果您不是,只需更改函数中的正则表达式应该仍然有效。
function ucAll($str) {
return preg_replace_callback('/([?!.]|^)'s*'w/', function($x) {
return strtoupper($x[0]);
}, $str);
}
我已经更新了您的正则表达式并使用了ucwords
而不是像 as 这样的strtoupper
function ucAll($str) {
return preg_replace_callback('/('w+)(?!=[.?!])/', function($m){
return ucwords($m[0]);
}, $str);
}
$str = ucAll("first.second.third");
echo $str;