简体   繁体   中英

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.

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

Use Stringy 在此输入图像描述

composer.json

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

PHP

Stringy::create('string')->toTitleCase()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM