Skip to content

All topics  /  PHP

Convert String To Sentence Case In PHP Example

PHP ·

Hi guys,

Today i will explained how to Convert String To Sentence Case In PHP. This example is so easy to use in php.

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.

So let's start to the example.

index.php


<?php
    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); 
    }
    $string = 'this is perfect sentence. this is not a another sentence. wow! what?';
    echo sentenceCase($string);
?>

Output

This is perfect sentence. This is not a another sentence. Wow! What?    

Now you can check your own.