驼峰式的字符串与下划线式的字符串互转作者:luke

<?php
$ts = microtime(true);
$r = 'open_door';
$s = '';
foreach(explode('_', $r) as $v){$s .= ucfirst($v);}
$t1 = microtime(true);
echo $s;
echo PHP_EOL,$t1 -$ts,PHP_EOL;

$s = ucwords(str_replace("_"," ",$r));
$t2 = microtime(true);
echo $s;
echo PHP_EOL,$t2 -$t1,PHP_EOL;

$s = preg_replace_callback('/(^|_)(\w)/', function ($mat){return strtoupper($mat[2]);}, $r);
$t3 = microtime(true);
echo $s;
echo PHP_EOL,$t3 -$t2,PHP_EOL;
<?php
$ts = microtime(true);
$r = 'open_door';
$s = '';
foreach(explode('_', $r) as $v){$s .= ucfirst($v);}
$t1 = microtime(true);
echo $s;
echo PHP_EOL,$t1 -$ts,PHP_EOL;

$s = ucwords(str_replace("_"," ",$r));
$t2 = microtime(true);
echo $s;
echo PHP_EOL,$t2 -$t1,PHP_EOL;

$s = preg_replace_callback('/(^|_)(\w)/', function ($mat){return strtoupper($mat[2]);}, $r);
$t3 = microtime(true);
echo $s;
echo PHP_EOL,$t3 -$t2,PHP_EOL;
//
$ts = microtime(true);
$r = 'OpenDoor';
$s = preg_replace_callback('/(^|.)([A-Z])/', function($m ){return ($m[1] ? "$m[1]_" : '') . strtolower($m[2]);}, $r);
$t1 = microtime(true);
echo $s;
echo PHP_EOL,$t1 -$ts,PHP_EOL;

$s = strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $r));
$t2 = microtime(true);
echo $s;
echo PHP_EOL,$t2 -$t1,PHP_EOL;

$s =  strtolower(substr(preg_replace('#[A-Z]#', '_$0', $r), 1));
$t3 = microtime(true);
echo $s;
echo PHP_EOL,$t3 -$t2,PHP_EOL;  
时间:2018-3-28 分类:练习