如何用PHP大写句子中的第一个字母?

时间:2012-01-21 07:30:42

标签: php text-segmentation

  

可能重复:
  How do I display the first letter as uppercase?
  PHP capitalize first letter of first word in a sentence

我想在句子中和句点之后大写第一个字母。谁能建议怎么做?

例如,

//I have the following in a language class.
"%s needs to identify areas of strength and 
weakness. %s sets goals for self-improvement."; 

// in a view
$contone=$this->lang->line($colstr);// e.g get the above string.
//$conttwo=substr($contone, 3);//skip "%s " but this doesnot work when there 
//are more than one %s
$conttwo=str_replace("%s ", "", $contone);// replace %s to none 
$contthree = ucfirst($conttwo); // this only uppercase the first one

我想要以下输出。

Needs to identify areas of strength and 
weakness. Sets goals for self-improvement.

2 个答案:

答案 0 :(得分:1)

请尝试以下操作。

它将运行该函数以在具有多个句子的字符串中的句点(句点)之后大写每个字母。

    $string = ucfirst(strtolower($string));     

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

    echo $string;

请做必要的更改。

答案 1 :(得分:0)

试试这个:

<?php
//define string
$string = "your sentences";

//first we make everything lowercase, and then make the first letter if the entire string capitalized
$string = ucfirst(strtolower($string));

//now we run the function to capitalize every letter AFTER a full-stop (period).
$string = preg_replace_callback('/[.!?].*?\w/', create_function('$matches', 'return strtoupper($matches[0]);'),$string);

//print the result
echo $string;

?>