当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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

网友答案:

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.

网友答案:

Use the ucwords function:

echo ucwords('hello world');
网友答案:

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

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

网友答案:

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
?>
网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: