Site Admin
Site Admin Founder of MeaningArticles
575 Views

Convert String To Sentence Case In PHP

Hello Dev.

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

<p>This is perfect sentence. This is not a another sentence. Wow! What?</p>

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.