I have a string in the format of $ str & quot; Chinese people's abc Republic x01 & quot;. How can I traverse this string one by one? That is, it can output "medium", "China", "people", and ""... my current method is: for ($ i0; $ I & amp; lt; len; $ I ++) {$ sub_strmb_substr ($ st... I have a string in the format of $ str = "Chinese people's abc Republican \ x01". How can I traverse this string one by one? That is, it can output "medium", "China", "people", and ""...
My current method is: for ($ I = 0; $ I <len; $ I ++) {$ sub_str = mb_substr ($ str, $ I, 1 )}, however, the efficiency is too low.
How can we improve efficiency? Can I convert $ str to an array?
Reply content:
I have a string in the format of $ str = "Chinese people's abc Republican \ x01". How can I traverse this string one by one? That is, it can output "medium", "China", "people", and ""...
My current method is: for ($ I = 0; $ I <len; $ I ++) {$ sub_str = mb_substr ($ str, $ I, 1 )}, however, the efficiency is too low.
How can we improve efficiency? Can I convert $ str to an array?
Function str_split_unicode ($ str, $ l = 0) {if ($ l> 0) {$ ret = array (); $ len = mb_strlen ($ str, "UTF-8 "); for ($ I = 0; $ I <$ len; $ I + = $ l) {$ ret [] = mb_substr ($ str, $ I, $ l, "UTF-8");} return $ ret;} return preg_split ("// u", $ str,-1, PREG_SPLIT_NO_EMPTY );} $ s = 'people of China abc Republican \ x01 status'; print_r (str_split_unicode ($ s )); array ([0] => Center [1] => China [2] => People [3] => People [4] => a [5] => B [6] => c [7] => [8] => and [9] => \ [10] => x [11] => 0 [12] => 1 [13] => country)
// UTF8 algorithm. convert other codes by yourself
$ 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) <192) {// if it is English, 1 byte if (substr ($ tempaddtext, $ cind, 1 )! = "") {Array_push ($ arr_cont, substr ($ tempaddtext, $ cind, 1) ;}$ cind ++;} elseif (ord (substr ($ tempaddtext, $ cind, 1) <224) {array_push ($ arr_cont, substr ($ tempaddtext, $ cind, 2); $ cind + = 2 ;} else {array_push ($ arr_cont, substr ($ tempaddtext, $ cind, 3); $ cind + = 3 ;}} print_r ($ arr_cont );