Home >Backend Development >PHP Problem >How to decompose a string into characters in php
First type:
$arr = str_split($str); p($arr);
Result:
Summary:
The str_split method is used directly to split, but unfortunately this method does not support Chinese parsing. Here you can consider the split of mb_split, and why here [sample] Will the two characters be divided into six garbled characters? It should be caused by utf8. One Chinese character in utf8 occupies 3 bytes, and one Chinese character in GBK and GB2312 occupies 2 bytes.
Second type:
$arr = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY); P($arr);
Result:
Summary:
Regular rules are used here to separate characters
preg_split(pattern, subject, limit, flags)
pattern: Pattern used for search, string form;
subject: Input string;
limit: how many characters are limited, -1|0|null means no limit
flags: PREG_SPLIT_NO_EMPTY (returns the separated non-empty part [commonly used]) PREG_SPLIT_DELIM_CAPTURE( Parenthesized expressions in delimited patterns will be captured and returned) PREG_SPLIT_OFFSET_CAPTURE (with the string offset appended to the return for each occurrence of a match).
Third type:
$len = mb_strlen($str, 'utf8'); $tmp = []; for ($i = 0;$i < $len;$i++) { $tmp[] = $str[$i]; } p($tmp);
Result:
Result:
Use a loop to cut the string, first get the length of the string, and then for loop, the last unknown character here is because $len = 7, so the cycle is 7 times, which is different from the utf8 character confusion problem of the first method.
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to decompose a string into characters in php. For more information, please follow other related articles on the PHP Chinese website!