Let's say i have a number 10000
and i want to split it by 2 characters from right to left resulting in array something like this [0] => 1,[1] => 00,[2] => 00
. Is it somehow possible with str_split($var, 2);
?
There must be easier ways, but you can use something like:
array_map("strrev", array_reverse(str_split(strrev(10000), 2)));
[0] => 1
[1] => 00
[2] => 00
You can use preg_split
to check positions where the number of digits until the end is even.
$result = preg_split('~\B(?=(..)+$)~', '10000');
\\B
the non-word boundary, prevents to match the start of the string. (The non-word boundary only matches between two digits)
(?=(..)+$)
is a lookahead that checks if the position is followed by an even number of characters.
Otherwise you can add a leading 0 when the string length is odd and remove it in the first item:
$str = '10000';
if ( strlen($str) & 1 ) {
$res = str_split("0$str", 2);
$res[0] = (int)$res[0];
} else {
$res = str_split($str, 2);
}
print_r($res);
or shorter using the ternary operator:
$result = str_split( strlen($str) & 1 ? "0$str" : $str, 2);
$result[0] = (int)$result[0];
好的,没关系,我可以做一些像strrev($string)
类的东西,然后将它拆分为2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.