我正在尝试编写一个函数来清理用户输入。
我并不想让它变得完美。我宁愿有几个小写的名字和缩写,也不愿有一个完整的大写段落。
我认为该函数应该使用正则表达式,但我对这些很不擅长,我需要一些帮助。
如果以下表达式后面跟着一个字母,我想将该字母设为大写。
"."
". " (followed by a space)
"!"
"! " (followed by a space)
"?"
"? " (followed by a space)
更好的是,该函数可以在“.”、“!”之后添加空格和 ”?”如果后面跟着一个字母。
如何实现这一点?
$output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input)));
由于修饰符 e 在 PHP 5.5.0 中已被弃用:
$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($input)));
这是按照您想要的方式执行的代码:
<?php
$str = "paste your code! below. codepad will run it. are you sure?ok";
//capitalize first letter and every letter after a . ? and ! followed by space
$str = preg_replace_callback('/(?:^|[.!?]\h+\W*)\w/',
function ($m) { return strtoupper($m[0]); }, $str);
// print the result
echo $str . "\n";
?>
输出:
Paste your code! Below. Codepad will run it. Are you sure?ok
使用
./!/?
作为分隔符将字符串分隔成数组。循环遍历每个字符串并使用 ucfirst(strtolower($currentString))
,然后再次将它们连接成一个字符串。
这个:
<?
$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.
请注意,您不必必须逃跑。!?在[]里面。
这个怎么样?没有正则表达式。
$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);
}
对我来说效果很好。
$output = preg_replace('/([\.!\?]\s?\w)/e', "strtoupper('$1')", $input)
$Tasks=["monday"=>"maths","tuesday"=>"physics","wednesday"=>"chemistry"];
foreach($Tasks as $task=>$subject){
echo "<b>".ucwords($task)."</b> : ".ucwords($subject)."<br/>";
}