header("Content-type: text/html; charset=utf-8");
//第一种方法
function arr_split_zh($tempaddtext){
$tempaddtext = iconv("UTF-8", "gb2312", $tempaddtext);
$cind = 0;
$arr_cont=array();
for($i=0;$i<strlen($tempaddtext);$i++)
{
if(strlen(substr($tempaddtext,$cind,1)) > 0){
if(ord(substr($tempaddtext,$cind,1)) < 0xA1 ){ //如果为英文则取1个字节
array_push($arr_cont,substr($tempaddtext,$cind,1));
$cind++;
}else{
array_push($arr_cont,substr($tempaddtext,$cind,2));
$cind+=2;
}
}
}
foreach ($arr_cont as &$row)
{
$row=iconv("gb2312","UTF-8",$row);
}
return $arr_cont;
}
//第二种正则
function test ( $str ) {
$temp = '';
for ( $i = 0; $i < strlen($str); $i++ ) {
if ( preg_match("/[\w\~\!\@\#\$\%\^\&\*\(\)\_\+\|\{\}\"\:\<\>\?\/\.\,\'\;\[\]\\\=\-\s]/", $str[$i]) ) {
$temp .= $str[$i] . "%";
} else {
$temp .= $str[$i] . $str[++$i] . $str[++$i] . "%";
}
}
return $temp;
}
//第三种递归
function t ( $str ) {
$temp = '';
$num = strlen($str);
for ( $i = 0; $i < $num; $i++ ) {
if (mb_detect_encoding($str[$i]) === false) {
$temp .= $str[$i];
} else {
$temp .= '%' . $str[$i];
}
}
return $temp;
}
//运行时间测试
function timeTest ( $num, $f ) {
$time = microtime(1);
for ( $i = 0; $i < $num; $i++ )
$f();
return microtime(1) - $time;
}
$string="SFEU-P-150303-3 法瑞意+新天鹅堡3-4* MU 罗马法兰 10晚12天";
echo timeTest( 10000, function () {global $string; arr_split_zh($string);} );
echo "<br>";
echo print_r(arr_split_zh($string));
echo "<br>";
echo timeTest( 10000, function () {global $string; t($string);} );
echo "<br>";
echo t($string);
echo "<br>";
echo timeTest( 10000, function () {global $string; test($string);} );
echo "<br>";
echo test($string);
近期评论