0

I've been trying for the couple of days to split a string into letters and numbers. I've found various solutions but they do not work up to my expectations (some of them only separate letters from digits (not integers or float numbers/per say negative numbers).

Here's an example:

$input = '-4D-3A'; // edit: the TEXT part can have multiple chars, i.e. -4AB-3A-5SD
$result = preg_split('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', $input);
print_r($result);

Result:

Array ( [0] => -4 [1] => D-3 [2] => A )

And I need it to be [0] => -4 [1] => D [2] => -3 [3] => A

I've tried doing several changes but no result so far, could you please help me if possible?

Thank you.

Crys Ex
  • 335
  • 1
  • 4
  • 9
  • Are there any variations with the example $input='-4D-3a' that you have given? –  Oct 29 '13 at 11:19
  • there will be probably a string matching {Number1}{Text1}{N2}{T2}{N3}{T3}...{Nn}{Tn} – Crys Ex Oct 29 '13 at 11:25
  • oh and yes the text can have more than one character, such as -3STS-5AB and it goes like -3, STS, -5, AB etc – Crys Ex Oct 29 '13 at 11:27

2 Answers2

2

try this:

$input = '-4D-3A';
$result = preg_split('/(-?[0-9]+\.?[0-9]*)/i', $input, 0, PREG_SPLIT_DELIM_CAPTURE);
$result=array_filter($result);
print_r($result);

It will split by numbers BUT also capture the delimiter (number)

giving : Array ( [1] => -4 [4] => D [5] => -3 [8] => A )

I've patterened number as:
1. has optional negative sign (you may want to do + too)
2. followed by one or more digits
3. followed by an optional decimal point
4. followed by zero or more digits

Can anyone point out the solution to "-0." being valid number?

Waygood
  • 2,657
  • 2
  • 15
  • 16
1

How about this regex? ([-]{,1}\d+|[a-zA-Z]+) I tested it out on http://www.rubular.com/ seems to work as you want.

alandarev
  • 8,349
  • 2
  • 34
  • 43
  • I see that it works but it splits all the characters whereas I need the {text} part from the string to be separated until it reaches the next number, i.e. -4TEST-5A it should turn into -4, TEST, -5, A Thanks! – Crys Ex Oct 29 '13 at 11:29
  • Sure, I will modify it. If you have more requirements, let us know, because all we have is a test case you gave. – alandarev Oct 29 '13 at 11:32