Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 520
JoAnne Avatar asked Jul 07 '15 02:07

JoAnne


2 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
like image 149
Juank Avatar answered Nov 03 '22 21:11

Juank


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

like image 27
chris85 Avatar answered Nov 03 '22 21:11

chris85