2017-05-02 18 views
3

我有一个小函数来更正用户条目,如果他们不在表单中大写他们的名字。解析用户输入表单上强制名称上的大写php

<pre> 
function fixWords($x){ 
    // define process 
    $x= strtolower($x); 
    $x= ucwords($x); 
    return $x; 
} 
</pre> 

我发现双名和复合名字没有得到大写字母。什么是分裂双打和连字符名称的最好办法,以迫使这些人的资本也。谢谢。

+0

和/或如果我的答案有帮助,请接受我的答案是正确的。欢呼声 –

+0

谢谢..我会尝试这两个并发回。 –

回答

1

您可以使用ucfirst()preg_replace_callback(),即:

function fixWords($name) 
{ 
    return preg_replace_callback('/\b\w/i', function($matches) { 
     return ucfirst(strtolower($matches[0])); 
    }, $name); 
} 

print fixWords("some name"); 
# Some Name 
print fixWords("some-name"); 
# Some-Name 

PHP Demo

+0

谢谢..我会尝试这两个并发回。 –

+0

佩德罗和斯特林 - 谢谢。我更喜欢Pedro的版本,因为preg_replace_callback()我可以添加不时出现的其他细微差别,比如'重音'字符前。 De'Chardin –

+0

Glod它解决了4你! –

1

在混合补充一点:

$xArr = explode('-', $x); 
$i = 0; 
while($i < count($xArr)) { 
    $xArr[$i] = ucfirst($xArr[$i]); 
    $i++; 
} 
$x = join('-', $xArr); 

http://php.net/manual/en/function.ucfirst.php

+1

我更喜欢'for()'和'implode()',但这几乎是我能想到的最干净的解决方案! – Zeke

+0

谢谢..我会尝试这两个并发回。 –

+0

佩德罗和斯特林 - 谢谢。我更喜欢Pedro的版本,因为preg_replace_callback()我可以添加不时出现的其他细微差别,比如'重音'字符前。 De'Chardin –