php如何让含有中文、字母、数字的字符串倒置?
网上的代码:
代码1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <?php $a='abcd闵LOVE军儿';//测试的字符串,包含中文西文 //下面的测试输出为上,因为在编码为utf-8时,一个中文字符占3个长度 //echo strlen('闵'); $b=''; $i=0; while($i<strlen($a)) { if(ord(substr($a,$i,1))>0xa0)//ord函数判断该字符串是否是中文 { $b=substr($a,$i,3).$b;//这句很重要,倒序! $i+=3; } else { $b=substr($a,$i,1).$b; $i++; } } echo $b; ?> </body> </html>
代码2:
<?php header("content-type:text/html;charset=utf-8"); $str = "1个中文字utf-8编码"; /** * $b utf-8用 3 , gb2312用2 */ function test($str , $b=3){ $length = strlen($str); $rets = ''; for($i = 0 ; $i<$length ; $i ++){ if(ord(substr($str , $i,1))>128){ $rets[] = substr($str ,$i,$b); $i += $b-1; }else{ $rets[] = substr($str, $i,1); } } return implode('' , array_reverse($rets)); } $test = test($str); var_dump($test); /** string(24) "码编8-ftu字文中个1" */
<?php header ( "content-type:text/html;charset=utf-8" ); function test($str, $b = 3) { $length = strlen ( $str ); $result = array (); $i = 0; while ( $i < $length ) { if (ord ( substr ( $str, $i, 1 ) ) > 0xa0) { $result [] = substr ( $str, $i, $b ); $i += $b; } else { $result [] = substr ( $str, $i, 1 ); $i ++; } } return implode ( "", array_reverse ( $result ) ); } $str = "flyhigh飞得lala更高ls"; $result = test ( $str ); echo $result; ?>
如果是单字节字符串可用strrev()函数反转字符串;