2013-04-10 44 views
0

$ details ['wasprice']的值包含單詞「was」(即$ 23.99)。我想刪除「was」一詞,並將該值保留爲「$ 23.99」。下面整理數組的某個值

代碼:

foreach($html->find('div.product-details-contents') as $content) { 
    $detail['img'] = $content->find('img.product-details-image',0)->src; 
    $detail['title'] = $content->find('span.title', 0)->plaintext; 
    $detail['units'] = $content->find('span.unit-size', 0)->plaintext; 
    $detail['wasprice'] = $content->find('span.was-price', 0)->plaintext; 
    $detail['nowprice'] = $content->find('span.special-price', 0)->plaintext; 

$product[] = $detail; 

} 

print_r($product); 

我只是想知道如何去這一點。

謝謝

+2

'$細節[ 'wasprice'] = str_replace函數( '是', '',$細節[ 'wasprice']);' – 2013-04-10 22:59:56

回答

0

使用PHP sanitize filter刪除非數字的所有內容,然後放回美元($)符號。

$newprice = "$".filter_var($wasprice, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND); 

在您的示例代碼使用它:

<?php 
foreach($html->find('div.product-details-contents') as $content) { 
    $detail['img'] = $content->find('img.product-details-image',0)->src; 
    $detail['title'] = $content->find('span.title', 0)->plaintext; 
    $detail['units'] = $content->find('span.unit-size', 0)->plaintext; 
    $detail['wasprice'] = "$".filter_var($content->find('span.was-price', 0)->plaintext, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND); 
    $detail['nowprice'] = $content->find('span.special-price', 0)->plaintext; 
    $product[] = $detail; 
} 
print_r($product); 
?> 
0

使用str_replace()

$detail['wasprice'] = str_replace('was ', '', $detail['wasprice']); 
+0

這做了幾個假設。 – miorel 2013-04-10 23:02:06

+0

這個地址OP的問題,並不是它的通用解決方案。 – 2013-04-10 23:02:53

+0

礦可能是「更普遍」,並處理奇怪的場景,但我同意@WebnetMobile解決OP問題。 – LawrenceGS 2013-04-11 00:44:36

0
if (substr($detail['wasprice'], 0, 4) === 'was ') { 
    $detail['wasprice'] = substr($detail['wasprice'], 4); 
} else { 
    // ruh-roh 
} 
0

我會用preg_replace()更換$事情之前:

$detail['wasprice'] = preg_replace('/([^$]*)(.*)/', '$2', $detail['wasprice']); 
0

第三個解決方案:

$detail['wasprice'] = ltrim($detail['wasprice'], " asw");