开发者

How to convert a string to an integer?

<?php

header('Content-type: text/html; charset=gb2312');

include("parser.php");

$html = file_get_html('http://www.souyishop.com/shop_gkq5/1280/products.aspx?sku=1351249&shbid=20358');

$price = $html->find('span[id=Product_main1_Label5]');
$price = str_replace(" ", "", str_replace("¥", "", str_replace("元", "", $price[0])));

echo (int)$price . "<br>";

?>

Basically, I'm trying to fetch the price ¥ 32 元 and I remove the currency and white space. After that I try to convert the string to int开发者_如何转开发 so that I can do calculation later. Guess what, I get 0. :(


Somethign like this isnt going to work:

echo intval('¥ 32');

So try replacing all nondigits

echo (int)preg_replace( '~\D~', '', $str );


Use a regular expression in this case:

$re = preg_match('/(\d+)/', $str, $matches);
$price = $matches[1];


That str_replace chain is cumbersome

A more elegant solution is to pull out all numbers with preg_match

$price = preg_match('/[0-9]+/i', $price, $matches);
print_r($matches);


I think you should first echo $price without and int conversion to determine if you are actually replacing the string items you think you are, this is probably why it returns 0.

Chinese encoding requires special handling.

edit:

try using the html code for the char (yen = &#165;) see: http://www.starr.net/is/type/htmlcodes.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜