简体   繁体   中英

How to str_split string from right to left?

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

  1. strrev() - Reverse a string
  2. str_split() - Convert a string to an array
  3. array_reverse() - Return an array with elements in reverse order
  4. array_map() - Applies the callback to the elements of the given arrays

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM