admin管理员组

文章数量:1125561

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);

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);
Share Improve this question edited 2 days ago Youri asked 2 days ago YouriYouri 133 bronze badges 2
  • What is the difference? Just spaces around? – Markus Zeller Commented 2 days ago
  • sorry, they need to be on the next line, I have updated my question – Youri Commented 2 days ago
Add a comment  | 

1 Answer 1

Reset to default 0

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
)

本文标签: preg matchphp pregmatch finding string between two pattersStack Overflow