1

这是我需要提取价格的数据字符串示例。

“价格 475 000 卢比 - 雪佛兰 AVEO LS // 9 月 11 日 6,000 公里 - 红色.. 完整选项.. 手动 5 门 // 掀背车联系我,电话 786 8394”

在爬取特定网站后,我有很多这样的字符串,字符串中可以有任何数字或单词。

我试图用空格分隔每个单词并将其存储在数组 $arr 中。我已经声明了另一个数组来存储价格 $arrPrice 的标识符。如果找到单词 price 或 rs,则数据(例如 475 000)存储在变量 $price 中。然而,由于我已经用空间爆炸了它,它没有考虑到 000 。我在 xml 标记中只得到 475。

这样做的有效方法可能是使用正则表达式,但我不擅长它。如果有人可以帮助我,将不胜感激。

直到现在在我的代码下面找到,

谢谢!

    <?php


    foreach($html->find('div.field-content') as $e) {//find the h3 element that contains class field content


    $arrPrice = array("rs", "price","rs."); // an array of identifiers to retrieve price

    $str = $e->innertext;// crawled data from a website
    $str = strtolower($str); //converting string to lower case
    $arr = explode(" ", $str);//creating an array of the string by seperating it from the spaces

    if (strlen($str) > 0) {
        $price='';

        for ($i = 0; $i < sizeof($arr); $i++) {

            //finding price 
            for ($j = 0; $j < sizeof($arrPrice); $j++) {
                if ($arr[$i]==$arrPrice[$j]) {
                    $price = $arr[$i+1];
                    //echo 'Price='.$arr[$i+1];

                }
            }   

        }
        $xml.="<Cars>";
        $xml.="<Price>".$price."</Price>";
        $xml.="</Cars>";
    } 

    else {
        echo "String is blank";
    }


}

$file = fopen('data.xml','w');
if(!$file) {
    die('Error cannot create XML file');
}
fwrite($file,$xml);
fclose($file);

?>

4

1 回答 1

0
if ( $arr[$i] == $arrPrice[$j] ) {
  $price = $arr[$i+1];
  if ( isset( $arr[$i+2] ) && is_numeric( $arr[$i+2] ) ) {
    $price .= $arr[$i+2];
  }
}

等等..

于 2012-11-05T20:35:54.440 回答