我需要将总是小写的名字变成大写。使用preg_replace大写第一个字母的单词
例如john johnsson
- >John Johnsson
也:
jonny-bart johnsson
- >Jonny-Bart Johnsson
如何做到这一点用PHP?
我需要将总是小写的名字变成大写。使用preg_replace大写第一个字母的单词
例如john johnsson
- >John Johnsson
也:
jonny-bart johnsson
- >Jonny-Bart Johnsson
如何做到这一点用PHP?
<?php
//FUNCTION
function ucname($string) {
$string =ucwords(strtolower($string));
foreach (array('-', '\'') as $delimiter) {
if (strpos($string, $delimiter)!==false) {
$string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
}
}
return $string;
}
?>
<?php
//TEST
$names =array(
'JEAN-LUC PICARD',
'MILES O\'BRIEN',
'WILLIAM RIKER',
'geordi la forge',
'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n"); }
//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>
从关于PHP手册条目的评论ucwords
。
用正则表达式:
$out = preg_replace_callback("/[a-z]+/i",'ucfirst_match',$in);
function ucfirst_match($match)
{
return ucfirst(strtolower($match[0]));
}
我会用'preg_replace_callback'来写这个,但是把它打败了.. +1 – RobertPitt 2010-08-10 14:59:02
你也可以使用正则表达式:
preg_replace_callback('/\b\p{Ll}/', 'callback', $str)
\b
代表一个单词边界和\p{Ll}
介绍任何Unicode小写字母。 preg_replace_callback
将调用一个名为callback
为每个匹配功能,并与它的返回值替换匹配:
function callback($match) {
return mb_strtoupper($match[0]);
}
这里mb_strtoupper
用于打开匹配小写字母为大写。
如果您期待unicode字符......或者即使您不是,我仍建议使用mb_convert_case。当你有一个php函数时,你不需要使用preg_replace。
这就是我想出了(测试)...
$chars="'";//characters other than space and dash
//after which letters should be capitalized
function callback($matches){
return $matches[1].strtoupper($matches[2]);
}
$name="john doe";
$name=preg_replace_callback('/(^|[ \-'.$chars.'])([a-z])/',"callback",$name);
或者,如果你有PHP 5.3+这可能是更好的(未经测试):
function capitalizeName($name,$chars="'"){
return preg_replace_callback('/(^|[ \-'.$chars.'])([a-z])/',
function($matches){
return $matches[1].strtoupper($matches[2]);
},$name);
}
我的解决办法是有点比其他一些发布的更详细,但我相信它提供了最好的灵活性(您可以修改$chars
字符串来更改哪些字符可以分隔名称)。
请注意,这最初降低了整个字符串,这可能是也可能不是你想要的 - 如果它不是你想要的,你总是可以删除“strtolower”调用。 – 2010-08-10 14:53:45