2

说我有一个字符串

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

我想爆炸所以输出是

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

我在想类似下面的东西,但不知道要使用哪个正则表达式!

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

提前致谢

4

1 回答 1

3

尝试这个 :

$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']);

输出 :

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

另一个解决方案

根据 Dream Eater 的评论:更小的写法:(.*?\$\d+)\s。– Dream Eater 3 分钟前

我只是*在最后添加了它,它工作正常。

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

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

于 2013-03-27T07:26:18.507 回答