Blog
It's a Wonderful Life
驼峰与下划线字符串格式互换
开发中经常遇到需要把下划线命名格式的字符串修改为驼峰格式,或者相反。我把它包装成为一个函数,方便转换操作。
方法1:使用正则匹配。
<?php
/*
* @param string $str the string that needs to be transform
* @return depends on input, it'll return either camel-case or under-score string
**/
function str_formator($str)
{
if (strpos($str, '_'))
{
$pattern = '/(?:_)([\w]?)/i';
$ccstr = preg_replace_callback($pattern, function ($match) {
return strtoupper($match[1]);
}, $str);
return $ccstr;
}
else
{
$pattern = '/([A-Z])/';
$usstr = preg_replace_callback($pattern, function ($match) {
return '_' . strtolower($match[1]);
}, $str);
return $usstr;
}
}
方法2:使用数组与for
循环。
<?php
/*
* @param string $str the string that needs to be transform
* @return depends on input, it'll return either camel-case or under-score string
**/
function str_formator2($str)
{
if (strpos($str, '_'))
{
$arr = explode('_', $str);
$n = count($arr);
for ($i = 1; $i < $n; $i++)
{
$arr[$i][0] = strtoupper($arr[$i][0]);
}
$ccstr = implode('', $arr);
return $ccstr;
}
else
{
$n = strlen($str);
for ($i = 0; $i < $n; $i++)
{
$asc = ord($str[$i]);
if ($asc >= 65 && $asc <= 90)
{
$lower = chr($asc - 32);
$str[$i] = '_' . chr();
}
}
return $str;
}
}