Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the first char of a string lowercase in PHP?

Tags:

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 key in a different place with the first letter made lowercase.

like image 659
Joseph Avatar asked Nov 28 '22 12:11

Joseph


2 Answers

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.

like image 191
Gordon Avatar answered Nov 30 '22 22:11

Gordon


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);
like image 38
codaddict Avatar answered Dec 01 '22 00:12

codaddict