regex 如何将句子中第一个单词的第一个字母大写?

zbdgwd5y  于 7个月前  发布在  其他
关注(0)|答案(7)|浏览(83)

我试图写一个函数来清理用户输入。
我并不想让它变得完美,我宁愿用英文写几个名字和缩写,也不愿用英文写一整段。
我认为函数应该使用正则表达式,但我对这些很不好,我需要一些帮助。
如果下面的表达式后面跟着一个字母,我想把这个字母写成。

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

字符串
更好的是,该函数可以在“.",“!”和“?”后面添加一个空格,如果后面跟着一个字母的话。
如何实现这一点?

q5iwbnjs

q5iwbnjs1#

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

pkwftd7m

pkwftd7m2#

下面的代码可以按照你想要的方式执行:

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

weylhg0b

weylhg0b3#

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

laximzn5

laximzn54#

这一点:

<?
$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.

字符串
请注意,您不需要 * 逃离。!?在[]中。

sr4lhrrt

sr4lhrrt5#

不如这样吧,不用正则表达式

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

字符串
对我来说很好。

iugsix8n

iugsix8n6#

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

字符串

anauzrmj

anauzrmj7#

$Tasks=["monday"=>"maths","tuesday"=>"physics","wednesday"=>"chemistry"];

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

     echo "<b>".ucwords($task)."</b> : ".ucwords($subject)."<br/>";
}

字符串

相关问题