10

我正在尝试编写一个函数来清理用户输入。

我不想让它完美。我宁愿有一些小写的名字和首字母缩写词,也不愿用大写的完整段落。

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

如果下面的表达式后面跟着一个字母,我想把那个字母变成大写。

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

更好的是,该函数可以在“.”、“!”之后添加一个空格。和 ”?” 如果后面跟着一个字母。

如何做到这一点?

4

7 回答 7

33
$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)));
于 2011-03-21T21:10:23.753 回答
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";
?>

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

于 2011-03-21T21:02:02.833 回答
1

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

于 2011-03-21T20:57:51.730 回答
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.

请注意,您不必逃避。!?里面 []。

于 2011-03-21T21:08:21.530 回答
1

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

$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);
}

对我来说工作得很好。

于 2016-08-25T18:02:28.250 回答
0
$output = preg_replace('/([\.!\?]\s?\w)/e', "strtoupper('$1')", $input)
于 2011-03-21T21:05:42.190 回答
-2
$Tasks=["monday"=>"maths","tuesday"=>"physics","wednesday"=>"chemistry"];

foreach($Tasks as $task=>$subject){

     echo "<b>".ucwords($task)."</b> : ".ucwords($subject)."<br/>";
}
于 2018-12-17T16:00:38.050 回答