Skip to main content

Posts

Showing posts with the label preg_replace

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 f...