2010-08-10 141 views

回答

2
<?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

+1

请注意,这最初降低了整个字符串,这可能是也可能不是你想要的 - 如果它不是你想要的,你总是可以删除“strtolower”调用。 – 2010-08-10 14:53:45

1

用正则表达式:

$out = preg_replace_callback("/[a-z]+/i",'ucfirst_match',$in); 

function ucfirst_match($match) 
{ 
    return ucfirst(strtolower($match[0])); 
} 
+0

我会用'preg_replace_callback'来写这个,但是把它打败了.. +1 – RobertPitt 2010-08-10 14:59:02

6

你也可以使用正则表达式:

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用于打开匹配小写字母为大写。

+0

我喜欢这个,但是我认为在像这样的公共论坛上提倡使用/ e修饰符是有危险的,没有经验的程序员不会看到它的明显危险。 – mvds 2010-08-10 15:02:29

+0

@mvds:我改用它来代替使用'preg_replace_callback'。 – Gumbo 2010-08-10 15:02:58

+0

很好,然后+1 ;-) – mvds 2010-08-10 15:03:32

3

如果您期待unicode字符......或者即使您不是,我仍建议使用mb_convert_case。当你有一个php函数时,你不需要使用preg_replace。

0

这就是我想出了(测试)...

$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字符串来更改哪些字符可以分隔名称)。

相关问题