2011-03-21 121 views
8

我想写一个函数来清理用户输入。如何将句首字母的首字母大写?

我不是想让它完美。我宁愿用小写字母表示一些名字和缩略词,而不用大写字母的全段。

我认为这个函数应该使用正则表达式,但是我对这些很不好,我需要一些帮助。

如果下面的表达式后面跟着一个字母,我想让该字母大写。

"." 
". " (followed by a space) 
"!" 
"! " (followed by a space) 
"?" 
"? " (followed by a space) 

更好的是,该功能可以在“。”,“!”之后添加空格。和“?”如果那些后面跟着一封信。

这是如何实现的?

+1

好东西,它与论坛无关。而不是假设我想要做什么,如何帮助? – Enkay 2011-03-21 20:55:21

+2

你不需要任何更多的信息。我解释了我想要做的事。如果你能提供帮助,那么请这样做,但如果不能,请在别的地方去追踪。 – Enkay 2011-03-21 21:00:37

+2

@Dagon @Enkay请相互尊重。 @Dagon如果您想从@Enkay获得某些特定的内容,那么请问该如何处理? – marcog 2011-03-21 21:10:04

回答

30
$output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input))); 

由于修改é已被弃用的PHP 5.5.0:

$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) { 
    return strtoupper($matches[1] . ' ' . $matches[2]); 
}, ucfirst(strtolower($input))); 
+0

谢谢。这工作。 – Enkay 2011-03-21 21:23:36

+1

没有问题。:) – w35l3y 2011-03-21 23:05:57

+5

只是提醒,e修饰符已被弃用在PHP 5.5 – 2013-06-14 09:37:38

1

使用./!/?作为分隔符将字符串分隔成数组。遍历每个字符串并使用ucfirst(strtolower($currentString)),然后再将它们连接成一个字符串。

+0

有趣的采取。我会试一试。我希望稍微练习一下我的正则表达式,但这可以完成这项工作。谢谢。 – Enkay 2011-03-21 21:04:56

3

这里是做你想要的代码:

<?php 

$str = "paste your code! below. codepad will run it. are you sure?ok"; 

//first we make everything lowercase, and 
//then make the first letter if the entire string capitalized 
$str = ucfirst(strtolower($str)); 

//now capitalize every letter after a . ? and ! followed by space 
$str = preg_replace_callback('/[.!?] .*?\w/', 
    create_function('$matches', 'return strtoupper($matches[0]);'), $str); 

//print the result 
echo $str . "\n"; 
?> 

OUTPUT:Paste your code! Below. Codepad will run it. Are you sure?ok

+0

你不再需要create_function :))( – dynamic 2011-03-21 21:09:38

1
$output = preg_replace('/([\.!\?]\s?\w)/e', "strtoupper('$1')", $input) 
1

此:

<? 
$text = "abc. def! ghi? jkl.\n"; 
print $text; 
$text = preg_replace("/([.!?]\s*\w)/e", "strtoupper('$1')", $text); 
print $text; 
?> 

Output: 
abc. def! ghi? jkl. 
abc. Def! Ghi? Jkl. 

注意,你^h大逃亡。!?在[]内。

0

这个怎么样?没有正则表达式。

$letters = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' 
); 
foreach ($letters as $letter) { 
    $string = str_replace('. ' . $letter, '. ' . ucwords($letter), $string); 
    $string = str_replace('? ' . $letter, '? ' . ucwords($letter), $string); 
    $string = str_replace('! ' . $letter, '! ' . ucwords($letter), $string); 
} 

对我来说工作很好。