How to split a PHP string with Chinese characters

Source: Internet
Author: User

The results of the PHP tutorial function "Str_split" to split, will appear garbled, because the length of Chinese characters and English characters are not the same length. But we can create a new function to convert characters to ASCII values, and then by judging the length of different characters to correctly split the Chinese string, the results into an array, and finally use the PHP function "join" in the character Fu insert the percent sign

<?php
function Str_split_utf8 ($STR) {
$split = 1;
$array =array ();
For ($i =0 $i <strlen ($str)) {
$value =ord ($str [$i]);
if ($value >127) {
if ($value >=192&& $value <=223) $split = 2;
ElseIf ($value >=224 && $value <=239) $split = 3;
ElseIf ($value >=240 && $value <=247) $split = 4;
}else{
$split = 1;
}
$key =null;
For ($j =0 $j < $split; $j + +, $i + +) {
$key. = $str [$i];
}
Array_push ($array, $key);
}
return $array;
}
$string = "cloud-dwelling Community network Www.111cn.net";
$arr 1=str_split_utf8 ($string);
echo join ("%", $arr 1);
?>

Method Two

<?php
$STR = "Cloud Habitat Community Network: Http://www.111cn.net";
function Mbstringtoarray ($STR, $charset) {
$strlen =mb_strlen ($STR);
while ($strlen) {
$array []=mb_substr ($str, 0,1, $charset);
$str =mb_substr ($str, 1, $strlen, $charset);
$strlen =mb_strlen ($STR);
}
return $array;
}
$arr =mbstringtoarray ($str, "gb2312");
?>


Attention:

1, $charset variables for the Web page encoding, such as "gb2312" or "utf-8";

2, the use of a method requires the server must open Mbstring.dll extension, or code execution error, so for the use of virtual host friends, you can consider the use of the second method.

Method Two:

<?php
Function Str_to_arr ($str) {
  $l =strlen ($STR);
 for ($i =0 $i < $l $i + +) {
  $arr []=ord ($str [$i]) >127? $str [$i]. $str [+ + $i]: $str [$i];
 }
 return $arr;
}
$arr =str_to_arr ($STR);
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.