Search code examples
phppreg-match

php preg_match finding string between two patters


I have this string:

1 x red 1 x blue 3 x yellow

and I want to turn it into:

1 x red
1 x blue
3 x yellow

How can I do this please? I have tried using php preg_match but no luck

$description = "1 x red 1 x blue 3 x yellow";
preg_match('/[0-9] x (.*?){[0-9] x /',$description,$matches);
var_dump($matches);

Solution

  • I'd use preg_match_all() and then just provide the pattern for a single entity:

    $str = '1 x red 1 x blue 3 x yellow';
    preg_match_all('/\d+\s+x\s+\S+/', $str, $matches);
    print_r($matches);
    
    Array
    (
        [0] => Array
            (
                [0] => 1 x red
                [1] => 1 x blue
                [2] => 3 x yellow
            )
    
    )
    

    You might also use preg_split() where the split pattern is something like, non-digit before a space then digit after the space -- but I would imagine this is somewhat more fragile:

    print_r(preg_split('/(?<=\D) (?=\d)/', $str));
    
    Array
    (
        [0] => 1 x red
        [1] => 1 x blue
        [2] => 3 x yellow
    )