查找包含各种html标签PHP的字符串

时间:2016-05-22 12:56:20

标签: php

{
  "status" : "success",
  "prices" : [
    {
      "market_hash_name" : "AK-47 | Aquamarine Revenge (Battle-Scarred)",
      "price" : "9.77",
      "created_at" : 1463806291
    },
    {
      "market_hash_name" : "AK-47 | Aquamarine Revenge (Factory New)",
      "price" : "38.51",
      "created_at" : 1463822081
    },
    {
      "market_hash_name" : "AK-47 | Aquamarine Revenge (Field-Tested)",
      "price" : "17.8",
      "created_at" : 1463811694
    },
    {
      "market_hash_name" : "AK-47 | Aquamarine Revenge (Minimal Wear)",
      "price" : "26.0",
      "created_at" : 1463823062
    },
    {
      "market_hash_name" : "AK-47 | Aquamarine Revenge (Well-Worn)",
      "price" : "12.9",
      "created_at" : 1463832713
    },
    {
      "market_hash_name" : "AK-47 | Black Laminate (Battle-Scarred)",
      "price" : "6.36",
      "created_at" : 1463832092
    },
    {
      "market_hash_name" : "AK-47 | Black Laminate (Factory New)",
      "price" : "93.0",
      "created_at" : 1463800517
    },
    ]
}

当我试图通过价格和AK-47的preg_match循环时,我有以下问题黑色层压板(崭新出厂)它似乎找不到它

我使用了以下代码

$data = json_decode($json,true);
$prices = $data['prices'];
echo '<pre>';
$item = 'AK-47 | Black Laminate (Factory New)';
foreach($prices as $items ){
    foreach($items as $key=>$value){
        if(preg_match("/".$item."/i",$value )){
            echo $key."<br>";
            echo $value."<br>";
        }
    }
}
echo '</pre>';

关于我做错了什么的想法

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

使用preg_quote函数来转义正则表达式模式中使用的字符串中的特殊字符:

$data = json_decode($json,true);
$prices = $data['prices'];

$item = 'AK-47 | Black Laminate (Factory New)';
foreach ($prices as $items ){
    foreach ($items as $key => $value){
        if (preg_match("/". preg_quote($item) ."/i", $value )) {
            echo $key."<br>";
            echo $value."<br>";
        }
    }
}

输出:

market_hash_name
AK-47 | Black Laminate (Factory New)

http://php.net/manual/en/function.preg-quote.php

答案 1 :(得分:0)

问题在于RegEx模式,|()是正则表达式。

您可以使用preg_quote

尝试

 if (preg_match("/". preg_quote($item) ."/i", $value )) {

而不是

if(preg_match("/".$item."/i",$value )){

您也可以尝试将正则表达式更改为:

$item = 'AK-47 \| Black Laminate \(Factory New\)';