Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting php string to Title Case

I want to convert an input string to Title Case.

So, if I have an input string

Name: MR. M.A.D KARIM

I want to produce the following output string

Name: M.A.D Karim

And if I have an input string

Address: 12/A, ROOM NO-B 13

I want to produce

Address: 12/A, Room No-B 13

I want my output string to have a capital letter after any whitespace character, as well as after any of the following characters: ., -, /.

My current solution is

ucwords(strtolower($string));

But it leaves characters after ., - and / lowercased, while I want them to be uppercased.

like image 835
Atik Khan Avatar asked Nov 22 '14 08:11

Atik Khan


1 Answers

While not 100% correct for both of your input strings, mb_convert_case() is an excellent tool for this type of task because it is a single, native function.

To implement you custom handling for specific sequences in the input string, preg_replace_callback() is appropriate. I'll use multibyte safe pattern techniques so that the entire solution remains multibyte/unicode safe.

Code: (Demo)

function titleCaseSpecial($string)
{
    return preg_replace_callback(
        '~[/.-]\p{Ll}~u',
        function ($m) {
            return mb_strtoupper($m[0], 'UTF-8');
        },
        mb_convert_case($string, MB_CASE_TITLE, 'UTF-8')
    );
}

$strings = [
    'Name: MR. M.A.D KARIM',
    'Address: 12/A, ROOM NO-B 13'
];

var_export(
    array_map('titleCaseSpecial', $strings)
);

Output:

array (
  0 => 'Name: Mr. M.A.D Karim',
  1 => 'Address: 12/A, Room No-B 13',
)

P.s. I am assuming the missing Mr. in the question is just a posting error.

like image 139
mickmackusa Avatar answered Sep 28 '22 01:09

mickmackusa