Convert String to Sentence Case in PHP


In sentence case, the first character of an English sentence is capitalised and subsequent characters are lowercased, except for proper nouns and other words which are generally capitalised by a more specific rule. Converting string to sentence case is used in some cases in the web project. For example, you’ll display the string and text in the web page which had taken from the user, and you are not sure whether the text content case is properly formatted or not. On that case, you need to convert text to sentence case before displaying in the web page.

Using PHP, you can easily convert any string to sentence case. In this article, we are going to show you a simple PHP script for convert string to sentence case. For better usability, all PHP code will be grouped together in a function and you only need to use this function for convert text to sentence case.

sentenceCase() function accept one parameter ($string) and convert passed parametter value to sentence case. This function returns the string as sentence case.

function sentenceCase($string) { 
$sentences preg_split('/([.?!]+)/'$string, -1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); 
$newString ''
    foreach (
$sentences as $key => $sentence) { 
$newString .= ($key 1) == 0
ucfirst(strtolower(trim($sentence))) : 
$sentence.' '

Call sentenceCase() function and pass the string or text which you want to convert. sentenceCase() function will return the converted string.

$string 'this is a sentence. this is another sentence. wow! what?';

//Outputs: This is a sentence. This is another sentence. Wow! What?

Leave a reply

CodexWorld Newsletter

Subscribe CodexWorld updates via email and get every new post delivered to your inbox.