整理数组的某个值

问题描述:

$ 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

使用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); 
?> 

使用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

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

我会用preg_replace()更换$事情之前:

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

第三个解决方案:

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