I want to convert a street address to something like Title Case. It isn't quite Title Case as the letter at the end of a string of numbers should be upper case. eg 19A Smith Street.
I know I can change "19 smith STREET" to "19 Smith Street" using
$str = ucwords(strtolower($str))
but that converts "19a smith STREET" to "19a Smith Street".
How can I convert it to "19A Smith Street"?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With