tags:

views:

102

answers:

3

I cannot use strtolower as it affects all char. 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 palce with the first letter made lowercase.

+11  A: 

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 PHP5.3

Updated after comments. The function does now check 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 now.

Gordon
+1 but the custom lcfirst function should possibly check that the string isn't 0 length. It avoids the Notice that occurs when it is.
Yacoby
you should use mb_strlen instead of strlen as strlen counts unicode characters incorrectly. (i.e. strlen("abcä") == 5, mb_strlen("abcä") == 4)
dbemerlin
+2  A: 

Just do:

$str = "STACKoverflow";
$str[0] = strtolower($str[0]); // prints sTACKoverflow

and if you are using >=5.3 you can do:

$str = lcfirst($str);
codaddict
+1  A: 

use icfirst()

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

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