简体   繁体   中英

PHP string transform first character uppercase/lowercase

I have two types of strings, 'hello', 'helloThere'.

What I want is to change them so they read like: 'Hello', 'Hello There' depending on the case.

What would be a good way fo doing this?

Thanks

To convert CamelCase to different words:

preg_replace('/([^A-Z])([A-Z])/', "$1 $2", $string)

To uppercase all the words first letters:

ucwords()

So together:

ucwords(preg_replace('/([^A-Z])([A-Z])/', "$1 $2", $string))

Use the ucwords function:

Returns a string with the first character of each word in str capitalized, if that character is alphabetic.

The definition of a word is any string of characters that is immediately after a whitespace (These are: space, form-feed, newline, carriage return, horizontal tab, and vertical tab).

This will not split up words that are slammed together - you will have to add spaces to the string as needed for this function to work.

使用ucwords功能:

echo ucwords('hello world');

To make shure it works on other languages, the UTF-8 might be a good idea to implement. Im using this water proof for any languages in my wordpress installs.

$str = mb_ucfirst($str, 'UTF-8', true);

This make first letter uppercase and all other lowercase. If the third arg is set to false (default), the rest of the string is not manipulated. However, someone here might suggest an argument to re-use the function itself and mb uppercase each word after the first one, to be a more exact answer to the question.

// Extends PHP
if (!function_exists('mb_ucfirst')) {

function mb_ucfirst($str, $encoding = "UTF-8", $lower_str_end = false) {
    $first_letter = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding);
    $str_end = "";
    if ($lower_str_end) {
        $str_end = mb_strtolower(mb_substr($str, 1, mb_strlen($str, $encoding), $encoding), $encoding);
    } else {
        $str_end = mb_substr($str, 1, mb_strlen($str, $encoding), $encoding);
    }
    $str = $first_letter . $str_end;
    return $str;
}

}

/ Lundman

PHP has many string manipulation functions. ucfirst() would do it for you.

http://ca3.php.net/manual/en/function.ucfirst.php

you can use ucwords like everyone said... to add the space in helloThere you can do $with_space = preg_replace('/[AZ]/'," $0",$string); then ucwords($with_space);

use ucwords

<?php
$foo = 'hello world';
$foo = ucwords($foo);             // Hello world

$bar = 'BONJOUR TOUT LE MONDE!';
$bar = ucwords($bar);             // HELLO WORLD
$bar = ucwords(strtolower($bar)); // Hello World
?>

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