Question: How to split a string into its constituent characters in PHP?
For example hello -> [h, e, l, l, o] There are three methods:
This is the string that needs to be split: $str = 'Hello sample';
String length:
$len = mb_strlen($str, 'utf8');// 7
The first type:
$arr = str_split($str);
p($arr);Second type:
$arr = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
P($arr);preg_split(pattern, subject, limit, flags)
pattern: pattern used for search, string form;
subject: input string;
limit: how many characters to limit, -1|0|null means no limit
flags: PREG_SPLIT_NO_EMPTY (returns the delimited non-empty part [commonly used]) PREG_SPLIT_DELIM_CAPTURE (the bracket expression in the delimited pattern will be captured and returned) PREG_SPLIT_OFFSET_CAPTURE (the string offset will be appended to the return for each occurrence of the match)
The third type:
$len = mb_strlen($str, 'utf8');
$tmp = [];
for ($i = 0;$i < $len;$i++) {
$tmp[] = $str[$i];
}
p($tmp);