2013-04-13 45 views
0

我需要能夠在PHP中提取以下內容,並且這讓我發瘋。PHP正則表達式的百分比或貨幣

就拿以下字符串:

$text = "Nalgene Narrow-Mouth Loop-Top 16-oz. Water Bottle for $4 + pickup and %40 off at REI";

,一方面,我需要能夠提取:

$4 as extracted currency

%40 as extracted percentage

並區分哪一個是貨幣,哪個是百分比。

爲了使它有點複雜,我也應該抓住它,如果貨幣would'be了:

$4.11 or $ 4.10 (not the spacing and the comma)

,或者如果百分比會一直:

% 40 (note the spacing)

我真的被卡住了,謝謝..

+0

地球上數字之前寫的是百分號嗎? – Qtax

+0

你是對的;)但它發生......雜亂的飼料。 –

回答

1
$text = "Nalgene Narrow-Mouth Loop-Top 16-oz. Water Bottle for $4.3 + pickup and % 40 off at REI"; 
preg_match('/%([ 0-9]+?) /', $text, $matches); 
print_r($matches); 
preg_match('/\$([ .0-9]+?) /', $text, $matches); 
print_r($matches); 
+0

這已經很棒了!謝謝。但它並沒有拿起,例如:\t \t $ text =「Nalgene窄口環 - 頂級16盎司水瓶,現價$ 4.13」;如果4.13美元在線的末尾。我試圖刪除尾隨/之前的空間。它然後確實找到貨幣,但只有$ 4,所以它失去了逗號後面的所有東西... –

+0

@KoenKonings,嘗試'/%([0-9。+] /' – Qtax

+0

@KoenKonings,使用此代替/% ([0-9] *)/取出後只修整數據 – monkeyinsight