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);
?
PHP | explode() Function explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs.
PHP | str_split() Function The str_split() is an inbuilt function in PHP and is used to convert the given string into an array. This function basically splits the given string into smaller strings of length specified by the user and stores them in an array and returns the array.
Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With