php regex用于多个术语

时间:2012-08-13 06:52:40

标签: php regex

我有这个字符串(来自GoDaddy列出xml),我希望将每个值分配给一个变量:

Auction Type:Offer,拍卖结束时间:08/12/2012 05:57 AM(PDT),价格:$ 4,000,出价数量:0,域名年龄:0,Description:1234我宣布一个拇指战,1234ideclareathumbwar .com,交通:0,估价:$ 0,IsAdult:true

我的问题是,如何使用regexp?

我试过这个:

$re  = "Auction Type: (.+?), ";
$re .= "Auction End Time: (.+?) \(.+?\), ";
$re .= "Price: .(.+?), ";
$re .= "Number of Bids: (.+?), ";
$re .= "Domain Age: (.+?), ";
$re .= "Description: (.*?), ";
$re .= "Traffic: (\d*)(.*?)";
$re .= "Valuation: (.+?), ";
$re .= "IsAdult: (.+?), ";

if(preg_match("~".$re."~is",$description,$m)){
    $record = Array('auctiontype' => trim($m[1]),
        'endtime'     => strtotime($m[2]),
        'price'       => str2float($m[3]),
        'bids'        => trim($m[4]),
        'age'         => trim($m[5]),
        'description' => addslashes(trim($m[6])),
        'traffic'     => trim($m[7]),
        'valuation'   => trim($m[8]),
        'isadult'     => trim($m[9])
    );
}

但它不起作用。我可以请求帮助吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

$re  = "Auction Type: (.+?), ";
$re .= "Auction End Time: (.+?) \(.+?\), ";
$re .= "Price: .(.+?), ";
$re .= "Number of Bids: (.+?), ";
$re .= "Domain Age: (.+?), ";
$re .= "Description: (.*?), ";
$re .= "Traffic: (\d*)(.*?), ";
$re .= "Valuation: (.+?), ";
$re .= "IsAdult: (.+?)$";

您忘记了一个,我还将,更改为$以获取$ re的最后一部分

答案 1 :(得分:1)

正如Leon Kramer所说,你必须将你的最后一个元素改为:

$re .= "IsAdult: (.+)$";

并且,$re .= "Traffic: (\d*)(.*?), ";行还有2个组(即$ m [7]和$ m [8]),所以更改

$record = Array('auctiontype' => trim($m[1]),
    'endtime'     => strtotime($m[2]),
    'price'       => str2float($m[3]),
    'bids'        => trim($m[4]),
    'age'         => trim($m[5]),
    'description' => addslashes(trim($m[6])),
    'traffic'     => trim($m[7]),
    'valuation'   => trim($m[8]),
    'isadult'     => trim($m[9])
);

$record = Array('auctiontype' => trim($m[1]),
    'endtime'     => strtotime($m[2]),
    'price'       => str2float($m[3]),
    'bids'        => trim($m[4]),
    'age'         => trim($m[5]),
    'description' => addslashes(trim($m[6])),
    'traffic'     => trim($m[7]),
    'valuation'   => trim($m[9]),   // here
    'isadult'     => trim($m[10])   // and here
);

我不知道你想用$m[8]做什么,在给定的例子中是空的。