2016-02-29 109 views
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 

回答

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)是 “或者取得第一个字符”

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; 

输出:

第一。第二。第三

0

这是因为您的正则表达式只匹配您定义的标点符号集之后的字符,并且第一个字不符合其中之一。我建议进行以下更改:

首先,此组([?!.]|^)与字符串(^)的开头以及您试图替换的(可选)空格和单词字符之前的标点符号列表相匹配。以这种方式进行设置意味着,如果字符串的开头有空格,它应该仍然可以工作。其次,使用匿名函数而不是create_functionrecommended,如果您使用的PHP> = 5.3,那么您希望在这一点上(如果您不是,只需更改函数中的正则表达式仍然可以)。

function ucAll($str) { 
    return preg_replace_callback('/([?!.]|^)\s*\w/', function($x) { 
     return strtoupper($x[0]); 
    }, $str); 
} 
1

因为正则表达式需要有要的.一个,!?在前方的它它不大写的第一个字。第一个单词没有其中的一个字符。

这将做到这一点:

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

它采用正面看,背后做的.确保一个,!?,或行的开始,是在前期匹配字符串。

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; 
相关问题