大写"_"后面的字符, 三种方法及其时间比较

本文通过实验比较了三种不同的PHP字符串处理方法的性能:使用str_replace进行替换、使用explode和implode结合foreach进行转换以及利用正则表达式preg_replace_callback进行处理。通过微基准测试揭示了各种方法在执行速度上的差异。
$str = 'str_ab ae_dfe';
$time1 = microtime();
for($i = 0; $i<1000; $i++){
    str_replace(
        array(' ', '##'),
        array('', ' '),
        lcfirst(ucwords(str_replace(
            array(' ', '_'),
            array('##', ' '),
            $str
            )))
        );
}
$time2 = microtime();
$str = 'str_ab ae_dfe';
for($i = 0; $i<1000; $i++){
    $str = explode('_', $str);
    foreach($str as $k=>&$v){
        if($k == 0)
            continue;
        $v = ucfirst($v);
    }
    $str = implode('', $str);
}
$time3 = microtime();
echo $time2 - $time1;
echo '<br>';
echo $time3 - $time2;
echo '<br>';
$str = 'str_ab ae_dfe';
$t = microtime();
for($i = 0; $i < 1000; $i++){
    preg_replace_callback('|_(\w)|', function($matches){
        return strtoupper($matches[0]);
    }, $str);
}
echo microtime()-$t;
exit;

$str = explode('_', $str);
foreach($str as $k=>&$v){
    if($k == 0)
        continue;
    $v = ucfirst($v);
}
$str = implode('', $str);
echo $str;exit;


echo preg_replace('/_([a-z])/',strtoupper('\\1'),$str);

exit;



$arr = explode(' ', $str);
foreach($arr as &$v){
    $vv = ucwords(str_replace(array('-', '_'), ' ', $v));
    $v = str_replace(' ','',lcfirst($vv));    
}
$str = implode(' ', $arr);
echo $str;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值