How can I change 19a smith STREET to 19A Smith Street in php How can I change 19a smith STREET to 19A Smith Street in php php php

How can I change 19a smith STREET to 19A Smith Street in php


Another approach, longer but could be easier to tweak for other unforseen scenarios given that this is a very custom behavior.

$string = "19a smith STREET";// normalize everything to lower case$string = strtolower($string);// all words with upper case$string = ucwords($string);// replace any letter right after a number with its uppercase version$string = preg_replace_callback('/([0-9])([a-z])/', function($matches){    return $matches[1] . strtoupper($matches[2]);}, $string);echo $string;// echoes 19A Smith Street// 19-45n carlsBERG aVenue  ->  19-45N Carlsberg Avenue


Here's one route you could go using a regex.

$str = '19a smith STREET';echo preg_replace_callback('~(\d+[a-z]?)(\s+.*)~', function ($matches) {            return strtoupper($matches[1]) . ucwords(strtolower($matches[2]));        }, $str);

Output:

19A Smith Street

Regex demo: https://regex101.com/r/nS9rK0/2
PHP demo: http://sandbox.onlinephpfunctions.com/code/febe99be24cf92ae3ff32fbafca63e5a81592e3c


Based on the answer by Juank, I actually ended up using.

     $str = preg_replace_callback('/([0-9])([a-z])/', function($matches){           return $matches[1] . strtoupper($matches[2]);      }, ucwords(strtolower($str)));