Converting php string to Title Case

12.3k views Asked by At

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.

4

There are 4 answers

2
Rizier123 On BEST ANSWER

This should work for you:

<?php


    $str = "Name: MR. M.A.D KARIM";
    $result = "";

    $arr = array();
    $pattern = '/([;:,-.\/ X])/';
    $array = preg_split($pattern, $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

    foreach($array as $k => $v)
        $result .= ucwords(strtolower($v));

    //$result = str_replace("Mr.", "", $result); ->If you don't want Mr. in a String
    echo $result;



?>

Input:

Name: MR. M.A.D KARIM
Address: 12/A, ROOM NO-B 13

Output:

Name: M.A.D Karim
Address: 12/A, Room No-B 13
0
mickmackusa On

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.

0
Jonathan On

Use Stringy

composer.json

"require": {
    "voku/stringy": "~5.0"
}

PHP

Stringy::create('string')->toTitleCase()
3
DerSchinken On

I know this is 8 Years old but, ucwords already provides such functionality since PHP 5.4.32
It's as simple as:

<?php
echo ucwords(strtolower("Address: 12/A, ROOM NO-B 13"), ".-/ ");

https://www.php.net/manual/en/function.ucwords.php