在PHP中检查字符串中是否包含某些字符

时间:2016-09-15 11:10:21

标签: php string compare

我正在使用API​​检索法国公司的信息并输出此信息的自定义JSON。您输入公司名称,它会返回与搜索词匹配的所有公司信息。尽管如此,这个系统并非100%完美,因为它也使很多公司几乎与搜索价值相匹配。

例如,我搜索'abc'并在回报中我也得到名称为'abl'的公司。

所以我想在将它们放入结果数组之前对它们进行过滤。

public function transform($obj){

//The $obj is the information retrieved from the API in JSON.
    $data = json_decode($obj, true);
    $retval = array();

//The '$name = $data["params"]["name"];' is the name the API used as search parameter. 
    $name = $data["params"]["name"];

    foreach ($data["companies"] as $item){

//The '$item["names"]["best"]' is the name of the company.
        if(strpos($item["names"]["best"], $name) !== false){
            $retval[] = [
            "Company name" => $item["names"]["best"],
            "More info" => array(
                "Denomination" => $item["names"]["denomination"],
                "Commercial name" => $item["names"]["commercial_name"]
            ),
            "Siren number" => $item["siren"],
            "Street" => $item["address"],
            "Zip code" => $item["postal_code"],
            "City" => $item["city"],
            "Vat_number" => $item["vat_number"],
            "Established on" => $item["established_on"]
            ];
        }            
    }
    return json_encode($retval, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
}

但即使我在创建数组对象之前比较字符串,它仍会返回这些“错误”的公司。任何人都知道我做错了什么?任何帮助将不胜感激!

编辑:如果有人想知道我正在使用哪种API,请点击以下链接:https://firmapi.com/

1 个答案:

答案 0 :(得分:1)

使用preg_match()而不是strpos来查找完全匹配。希望这会对你有所帮助

public function transform($obj){

//The $obj is the information retrieved from the API in JSON.
    $data = json_decode($obj, true);
    $retval = array();

//The '$name = $data["params"]["name"];' is the name the API used as search parameter. 
    $name = $data["params"]["name"];

    foreach ($data["companies"] as $item){

//The '$item["names"]["best"]' is the name of the company.
        $string = 'Maramures';
        if ( preg_match("~\b$string\b~",$name) )
            $retval[] = [
            "Company name" => $item["names"]["best"],
            "More info" => array(
                "Denomination" => $item["names"]["denomination"],
                "Commercial name" => $item["names"]["commercial_name"]
            ),
            "Siren number" => $item["siren"],
            "Street" => $item["address"],
            "Zip code" => $item["postal_code"],
            "City" => $item["city"],
            "Vat_number" => $item["vat_number"],
            "Established on" => $item["established_on"]
            ];
        }            
    }
    return json_encode($retval, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
}