PHP實(shí)現(xiàn)駝峰命名和下劃線命名互轉(zhuǎn)
來(lái)源:涼官灰
發(fā)布時(shí)間:2020-05-13 09:57:21
閱讀量:1669
本篇文章教大家實(shí)現(xiàn)駝峰命名和下劃線命名互轉(zhuǎn),在php開(kāi)發(fā)中經(jīng)常需要兩種命名法互相轉(zhuǎn)換,下面為大家提供兩種實(shí)現(xiàn)方式.
第一種方法效率相對(duì)差一些,實(shí)現(xiàn)方式如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | function toUnderScore($str)
{
$dstr = preg_replace_callback('/([A-Z]+)/',function($matchs)
{
return '_'.strtolower($matchs[0]);
},$str);
return trim(preg_replace('/_{2,}/','_',$dstr),'_');
}
function toCamelCase($str)
{
$array = explode('_', $str);
$result = $array[0];
$len=count($array);
if($len>1)
{
for($i=1;$i<$len;$i++)
{
$result.= ucfirst($array[$i]);
}
}
return $result;
}
|
第二種方法更為巧妙高效,推薦使用第二種方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function camelize($uncamelized_words,$separator='_')
{
$uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}
function uncamelize($camelCaps,$separator='_')
{
return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));}
|