/*
参数:
$str_cut 需要截断的字符串
$length 允许字符串显示的最大长度
程序功能:截取全角和半角(汉字和英文)混合的字符串以避免乱码
*/
function substr_cut($str_cut,$length)
{
if (strlen($str_cut) > $length)
{
for($i=0; $i < $length; $i++)
if (ord($str_cut[$i]) > 128) $i++;
$str_cut = substr($str_cut,0,$i)."..";
}
return $str_cut;
}
?>
字符串转驼峰:
//微妙时间
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
//将下划线命名转换为驼峰式命名
function convertUnderline1 ( $str , $ucfirst = true)
{
while(($pos = strpos($str , '_'))!==false)
$str = substr($str , 0 , $pos).ucfirst(substr($str , $pos+1));
return $ucfirst ? ucfirst($str) : $str;
}
//将下划线命名转换为驼峰式命名
function convertUnderline2 ( $str , $ucfirst = true)
{
$str = explode('_' , $str);
foreach($str as $key=>$val)
$str[$key] = ucfirst($val);
if(!$ucfirst)
$str[0] = strtolower($str[0]);
return implode('' , $str);
}
//将下划线命名转换为驼峰式命名
function convertUnderline3 ( $str , $ucfirst = true)
{
$str = ucwords(str_replace('_', ' ', $str));
$str = str_replace(' ','',lcfirst($str));
return $ucfirst ? ucfirst($str) : $str;
}
//将下划线命名转换为驼峰式命名
function convertUnderline4 ( $str , $ucfirst = true)
{
$str = preg_replace('/_([A-Za-z])/e',"strtoupper('$1')",$str);
return $ucfirst ? ucfirst($str) : $str;
}
//将下划线命名转换为驼峰式命名
function convertUnderline5 ( $str , $ucfirst = true)
{
$str = preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches){
return strtoupper($matches[2]);
},$str);
return $ucfirst ? ucfirst($str) : $str;
}
效率由高到低为 方法3>方法2>方法1>方法4>方法5
驼峰转下划线:
echo strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', 'fooBar'));
//output:foo_bar
echo "<br>";
echo strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', 'foo'));
//output:foo
echo "<br>";
echo strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', 'fooBarB'));
//output:foo_bar_b
echo "<br>";