Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top