Root
Root

Reputation: 2349

Regex to split numbers from letters

I want to split number and letters from string but have problem .
Inputs like:
input example 1 : A5
input example 2 : C16
input example 3 : A725
input example 4 : X05
Result must be:
Result example 1 :'A','5'
Result example 2 : 'C','16'
Result example 3 : 'A','725'
Result example 4 : 'X','05'

I try to it with belo regex but don't give a good result :
preg_split('/(?=\d+)/', $input)

Upvotes: 0

Views: 159

Answers (2)

anubhava
anubhava

Reputation: 784998

You can use:

$s = 'A5,C16,A725,X05';
if (preg_match_all("~(?>[a-z]+|\d+)~i", $s, $arr))
   var_dump($arr[0]);

gives:

array(8) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "5"
  [2]=>
  string(1) "C"
  [3]=>
  string(2) "16"
  [4]=>
  string(1) "A"
  [5]=>
  string(3) "725"
  [6]=>
  string(1) "X"
  [7]=>
  string(2) "05"
}

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213223

You also need to add a negative look-behind to make sure the empty string that is chosen is not somewhere in the middle of two digits.

Currently for string A725, your regex will split on the empty string before 7, 2 and 5, as all of them are followed by at least one digit.

You can use this regex:

preg_split('/(?<!\d)(?=\d+)/', $input)

Upvotes: 3

Related Questions