如何在PHP中使字符串小写的第一个字符串?

时间:2010-05-10 10:13:07

标签: php

我无法使用strtolower,因为它影响所有char。我应该使用某种正则表达式吗?

我收到的是一个产品代码字符串,我希望将此产品代码用作不同位置的搜索键,第一个字母为小写字母。

5 个答案:

答案 0 :(得分:17)

尝试

  • lcfirst - 将字符串的第一个字符设为小写

和PHP< 5.3将其添加到全局范围:

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

上述优点仅仅是strolower所需要的是,一旦升级到PHP5.3,您的PHP代码将简单地切换到本机函数

评论后更新。该函数现在检查字符串中是否确实存在第一个字符,并且它是当前语言环境中的字母字符。它现在也是多字节的。

答案 1 :(得分:9)

只是做:

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

如果您使用的是>=5.3,则可以执行以下操作:

$str = lcfirst($str);

答案 2 :(得分:1)

使用icfirst()

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

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

答案 3 :(得分:0)

对于字符串的多字节第一个字母,以上示例都不起作用。 在这种情况下,您应该使用:

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

答案 4 :(得分:0)

ucfirst()函数将字符串的第一个字符转换为大写。

相关功能:

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+

相关问题