Convert String to Sentence Case in PHP

convert-string-to-sentence-case-php-codexworld

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.' '
    } 
    return 
trim($newString); 
}

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?';
echo 
sentenceCase($string);

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

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Mochamad Rizki Said...
  2. Bharath Said...

Leave a reply

keyboard_double_arrow_up