2

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

Passerby
  • 9,715
  • 2
  • 33
  • 50
pessato
  • 501
  • 6
  • 17

1 Answers1

3

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

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • Smaller way to write it: `(.*?\$\d+)\s`. – hjpotter92 Mar 27 '13 at 07:29
  • This appeared to work on initial testing however now if the value after the dollar sign has a .5 or .6 etc that value disappears from the output array. So as an example 1 x Shipping @ $1.5 becomes.. [KEY] => 1 x Shipping @ $1 .. any ideas?? thanks! – pessato Mar 31 '13 at 02:15
  • First solution works fine for me. when I gave input as `$str = '1 x Book @ $20 32 x rock music cd @ $.5 1 x shipping to india @ $10.5';` there is `$.5` in it, I got the output as `Array ( [0] => 1 x Book @ $20 [1] => 32 x rock music cd @ $.5 [2] => 1 x shipping to india @ $10.5 )` – Prasanth Bendra Apr 01 '13 at 04:22
  • Yes first solution works, thanks, still have a problem however as some of the items have a "&" character in the description for example 1 x Book & CD @ $10 when the & character is there the first solution does not work. Second solution works however not for the decimal place so cannot use. Any ideas?? Thank-you so much for your time. – pessato Apr 01 '13 at 07:29
  • have figured out a solution - preg_match_all('/(.*\$[\d\.]+)\s*/',$str,$match); - thanks everybody – pessato Apr 01 '13 at 08:18