pessato
pessato

Reputation: 501

Explode string after price

Say I have a string

$what = "1 x Book @ $20 32 x rock music cd @ $400 1 x shipping to india @ $10.5";

And I want to explode so that output is

Array 
(
    [0] => 1 x Book @ $20
    [1] => 32 x rock music cd @ $400
    [2] => 1 x shipping to india @ $10.50
)

I am thinking something like below but dont know which regular expressions to use!

 $items = preg_split('/[$????]/', $what);

Thanks in advance

Upvotes: 2

Views: 266

Answers (1)

Prasanth Bendra
Prasanth Bendra

Reputation: 32790

Try this :

$str = '1 x Book @ $20 32 x rock music cd @ $400 1 x shipping to india @ $10.5';
preg_match_all('/(?P<match>\d+\s+x\s+[\w\s]+\s+@\s+\$[\d\.]+)/',$str,$match);

echo "<pre>";
print_r($match['match']);

Output :

Array
(
    [0] => 1 x Book @ $20
    [1] => 32 x rock music cd @ $400
    [2] => 1 x shipping to india @ $10.5
)

Another solution :

As per Dream Eater' comment : Smaller way to write it: (.*?\$\d+)\s. – Dream Eater 3 mins ago

I just added * at the end and it works fine.

$str = '1 x Book @ $20 32 x rock music cd @ $400 1 x shipping to india @ $10.5';
preg_match_all('/(.*?\$\d+)\s*/',$str,$match);

echo "<pre>";
print_r($match);

Ref: http://php.net/manual/en/function.preg-match.php

Upvotes: 3

Related Questions