2

我有一个函数假设将所有句子的第一个字符变成大写,但由于某种原因,它没有对第一个句子的第一个字符执行此操作。为什么会发生这种情况,我该如何解决?

<?php

function ucAll($str) {

$str = preg_replace_callback('/([.!?])\s*(\w)/', 
create_function('$matches', 'return strtoupper($matches[0]);'), $str);
return $str;

} //end of function ucAll($str)

$str = ucAll("first.second.third");
echo $str;

?>

结果:

first.Second.Third

预期结果:

First.Second.Third
4

5 回答 5

1

它不会将第一个单词大写,因为正则表达式要求在其中一个或.前面。第一个单词前面没有这些字符。!?

这会做到:

function ucAll($str) {
    return preg_replace_callback('/(?<=^|[\.\?!])[^\.]/', function ($match) {
        return strtoupper($match[0]);
    }, $str);
}

它使用积极的后视来确保., !,?或行首之一位于匹配字符串的前面。

于 2016-02-29T05:05:20.493 回答
0

我已经更新了你的正则表达式并使用ucwords而不是strtoupper

function ucAll($str) {
    return preg_replace_callback('/(\w+)(?!=[.?!])/', function($m){
        return ucwords($m[0]);
    }, $str);
}
$str = ucAll("first.second.third");
echo $str;
于 2016-02-29T05:48:25.310 回答
0

尝试这个

function ucAll($str) {

$str = preg_replace_callback('/([.!?])\s*(\w)|^(\w)/', 
create_function('$matches', 'return strtoupper($matches[0]);'), $str);
return $str;

} //end of function ucAll($str)

$str = ucAll("first.second.third");
echo $str;

|^(\w)是“或获得第一个字符”

于 2016-02-29T03:12:35.417 回答
0

发生这种情况是因为您的正则表达式仅匹配您定义的一组标点符号之后的字符,并且第一个单词不跟随其中一个。我建议进行以下更改:

首先,该组([?!.]|^)匹配字符串 ( ^) 的开头以及您尝试替换的(可选)空格和单词字符之前的标点符号列表。以这种方式设置它意味着如果字符串的开头有任何空格,它仍然应该工作。

create_function其次,如果您使用的是 PHP >= 5.3,则建议您使用匿名函数,而不是使用匿名函数,希望您在这一点上(如果不是,只需更改函数中的正则表达式应该仍然有效。)

function ucAll($str) {
    return preg_replace_callback('/([?!.]|^)\s*\w/', function($x) {
        return strtoupper($x[0]);
    }, $str);
}
于 2016-02-29T04:45:23.473 回答
0

像这样的东西:

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

            } //end of function ucAll($str)
$str = ucAll("first.second.third");
echo $str;

输出 :

第一的。第二。第三

于 2016-02-29T03:31:05.833 回答