Format Sentences, format number and remove extra spaces. All in one solution

We had a requirement, where we were asked to format the content from a big database table. And the format includes making sentences to sentence case, format simple numbers to comma separated numbers within those sentences and remove the extra spaces. Here is the solution. Hope this helps you.
function formatString($string){
 //number formatting
 $string1 = preg_replace_callback('/\d+/', function($match){return number_format($match[0]);}, $string);
 
 //removing extra spaces
 $string2 = preg_replace('/\s+/', ' ', $string1);
 
 //sentence case
 $sentences = preg_split('/([.?!]+)/', $string2, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}

$str = "it was an awesome               day. i bought shares for 23000      and sold at 27000 in just 2        hours. i had a profit of 4000 INR. isn't it great?";
echo formatString($str);

No comments:

Post a Comment

Want to tell something about this post. Please feel free to write...