Home » Php » 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

Posted by: admin July 12, 2020 Leave a comment


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”?

How to&Answers:

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);


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))); 


You can split the line into 2 substrings, format each half separately, and then put the 2 substrings back together again.

$str = '19a smith STREET';
$split = strpos($str, ' ');
$str1 = strtoupper(substr($str, 0, $split + 1));
$str2 = ucwords(strtolower(substr($str, $split + 1)));
$str = $str1 . $str2;
echo $str;

Result: 19A Smith Street

PHP demo: http://sandbox.onlinephpfunctions.com/code/9119643624c77b0c9cc584150e556a5d92c92981