Search code examples
phpregexsplittext-extractionpreg-split

Split string after each number


I have a database full of strings that I'd like to split into an array. Each string contains a list of directions that begin with a letter (U, D, L, R for Up, Down, Left, Right) and a number to tell how far to go in that direction.

Here is an example of one string.

$string = "U29R45U2L5D2L16";

My desired result:

['U29', 'R45', 'U2', 'L5', 'D2', 'L16']

I thought I could just loop through the string, but I don't know how to tell if the number is one or more spaces in length.


Solution

  • You can use preg_split to break up the string, splitting on something which looks like a U,L,D or R followed by numbers and using the PREG_SPLIT_DELIM_CAPTURE to keep the split text:

    $string = "U29R45U2L5D2L16";
    print_r(preg_split('/([UDLR]\d+)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
    

    Output:

    Array (
        [0] => U29
        [1] => R45
        [2] => U2
        [3] => L5
        [4] => D2
        [5] => L16 
    )
    

    Demo on 3v4l.org