Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to str_split string from right to left?

Tags:

php

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); ?

like image 475
Jirka Kastan Avatar asked Jul 15 '18 13:07

Jirka Kastan


People also ask

How can I split a string into two parts in PHP?

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.

How do I split a character in a string in PHP?

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.

How do you separate characters numbers and special characters from given string in PHP?

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 (” “).


2 Answers

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
like image 69
Pedro Lobito Avatar answered Oct 15 '22 09:10

Pedro Lobito


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];
like image 25
Casimir et Hippolyte Avatar answered Oct 15 '22 09:10

Casimir et Hippolyte