2013-03-27 145 views
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); 

預先感謝

+0

使preg_split丟棄的分隔符,所以我會去另一個解決方案,如提出Prasanth Bendra。 – 2013-03-27 07:27:53

回答

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]+\[email protected]\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

+0

更小的寫法:'(。*?\ $ \ d +)\ s'。 – hjpotter92 2013-03-27 07:29:08

+0

這似乎適用於初始測試,但現在如果美元符號之後的值具有.5或.6等值,則該值將從輸出數組中消失。所以作爲例子1 x Shipping @ $ 1.5變成.. [KEY] => 1 x運輸@ $ 1 ..任何想法??謝謝! – pessato 2013-03-31 02:15:16

+0

第一種解決方案適用於我。當我輸入爲'$ str ='1 x Book @ $ 20 32 x搖滾音樂cd @ $ .5 1 x發貨至印度@ $ 10.5';'裏面有$ .5',我得到的輸出是'陣列 ( [0] => 1×書@ $ 20 [1] => 32×搖滾音樂CD @ $ .5 [2] => 1×航運至印度@ $ 10.5 )' – 2013-04-01 04:22:33