How to uppercase the first letter in a sentence in PHP? [duplicate]

前提是你 提交于 2019-12-25 05:17:05

问题


Possible Duplicate:
How do I display the first letter as uppercase?
PHP capitalize first letter of first word in a sentence

I want to uppercase the first letter in a sentence and after a period. Can anyone suggest how to do?

For example,

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

I want the following output.

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

回答1:


Try below.

It will run the function to capitalize every letter AFTER a full-stop (period) in a string having multiple sentences.

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

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

    echo $string;

Please do required changes.




回答2:


Try this:

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

?>


来源:https://stackoverflow.com/questions/8951436/how-to-uppercase-the-first-letter-in-a-sentence-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!