PHP字符串转换第一个字符大写/小写

时间:2010-08-05 14:47:52

标签: php uppercase lowercase

我有两种类型的字符串'hello', 'helloThere'.

我想要的是改变它们,使它们读起来像'Hello', 'Hello There',具体取决于具体情况。

这样做会有什么好办法?

由于

7 个答案:

答案 0 :(得分:7)

将CamelCase转换为不同的单词:

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

将所有单词首字母大写:

ucwords()

所以一起:

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

答案 1 :(得分:5)

使用ucwords功能:

  

返回第一个字符串   str中每个单词的字符   大写,如果那个角色是   字母。

     

单词的定义是任何字符串   直接的字符   在一个空白之后(这些是:空间,   换页,换行,回车,   水平标签和垂直标签。)

这不会拆分同时被抨击的单词 - 您必须根据需要为字符串添加空格才能使用此函数。

答案 2 :(得分:4)

使用ucwords功能:

echo ucwords('hello world');

答案 3 :(得分:1)

PHP有许多字符串操作函数。 ucfirst()会为你做的。

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

答案 4 :(得分:1)

您可以像所有人一样使用ucwords ...在helloThere $with_space = preg_replace('/[A-Z]/'," $0",$string);中添加空格ucwords($with_space);然后{{1}}

答案 5 :(得分:1)

使用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
?>

答案 6 :(得分:1)

为了使shure适用于其他语言,UTF-8可能是一个好主意。我在我的wordpress安装中使用这种防水语言。

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

这使得第一个字母大写,所有其他小写。如果第三个arg设置为false(默认值),则不会操纵字符串的其余部分。但是,这里有人可能会建议重新使用函数本身的参数,并在第一个单词之后用mb大写每个单词,以便更准确地回答问题。

// 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;
}

}

/伦德曼