开发者

How can I make the first character of a string lowercase in PHP?

I cannot use strtolower as it affects all characters. Should I use some sort of regular expression?

I'm getting a string which is a product code. I want to use this product code as a search ke开发者_StackOverflowy in a different place with the first letter made lowercase.


Try

  • lcfirst — Make a string's first character lowercase

and for PHP < 5.3 add this into the global scope:

if (!function_exists('lcfirst')) {

    function lcfirst($str)
    {
        $str = is_string($str) ? $str : '';
        if(mb_strlen($str) > 0) {
            $str[0] = mb_strtolower($str[0]);
        }
        return $str;
    }
}

The advantage of the above over just strolowering where needed is that your PHP code will simply switch to the native function once you upgrade to PHP 5.3.

The function checks whether there actually is a first character in the string and that it is an alphabetic character in the current locale. It is also multibyte aware.


Just do:

$str = "STACK overflow";
$str[0] = strtolower($str[0]); // prints sTACK overflow

And if you are using 5.3 or later, you can do:

$str = lcfirst($str);


Use lcfirst():

<?php
    $foo = 'HelloWorld';
    $foo = lcfirst($foo);             // helloWorld

    $bar = 'HELLO WORLD!';
    $bar = lcfirst($bar);             // hELLO WORLD!
    $bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>


For a multibyte first letter of a string, none of the previous examples will work.

In that case, you should use:

function mb_lcfirst($string)
{
    return mb_strtolower(mb_substr($string, 0, 1)) . mb_substr($string, 1);
}


The ucfirst() function converts the first character of a string to uppercase.

Related functions:

  • lcfirst() - converts the first character of a string to lowercase
  • ucwords() - converts the first character of each word in a string to uppercase
  • strtoupper() - converts a string to uppercase
  • strtolower() - converts a string to lowercase

PHP version: 4 and later

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜