如何使用PHP代码郊区名称进行搜索并将代码一起发布

时间:2016-11-28 10:47:46

标签: php

任何人都可以告诉我,我将搜索郊区名称并一起发布代码。我的PHP代码仅适用于以下组合。 (更多细节市郊名称:Rose Bay,邮政编码2029) 可以搜索

  • rosebay2029
  • 2029rosebay

无法搜索

  • rose bay2029
  • rosebay 2029
  • rose bay 2029
  • ROSE-BAY 2029
  • 2029 rosebay
  • 2029玫瑰湾
  • 2029rose bay

您能告诉我如何改进我的PHP代码所有组合(9)搜索。

$serchkey = isset($_POST['search'])? $_POST['search'] : "0000  map";
$value=explode(" ",$serchkey);
$suburbsname= urlencode(str_replace("-","",$value[0]));
$postcode = preg_replace('/[^0-9]/', '', $suburbsname);
$suburbs = preg_replace('/[^a-zA-Z]/','', $suburbsname);
$result = mb_substr($suburbs, 0, 4); // I need to display suburbs name first 4 letters
$geturlcontent = "http://myurl/Data?pcode=".$postcode."&SuburbName=".$result;    
echo $suburbsname."<br>";
echo $suburbs."<br>";
echo $postcode."<br>";

2 个答案:

答案 0 :(得分:1)

此函数将删除所有非字母数字字符,并在字符串中查找郊区和邮政编码:

function searchFunction($searchKey){
    $searchKey = preg_replace('/[^a-zA-Z0-9]/i', '', $searchKey);
    $suburbs = "";
    $postCode = "";
    $lastCharString = false;
    $numericCount = 0;
    for($i = 0; $i<strlen($searchKey); $i++){
        $isNumeric = is_numeric($searchKey[$i]);
        if($lastCharString && $isNumeric && $numericCount > 0){
            return false; // Mixed search string like ro0sebay20
        }
        if(!$isNumeric){
            $suburbs.=$searchKey[$i];
            $lastCharString = true;
        }else{
            $numericCount++;
            $lastCharString = false;
            $postCode.=$searchKey[$i];
        }
    }
    return array( 'suburbs' => $suburbs, 'postCode' => $postCode );
}

您可以通过以下方式查看测试结果:

var_dump(searchFunction("rose bay2029")); // suburbs = rosebay, postCode = 2029
var_dump(searchFunction("000-0 map")); // suburbs = map , postCode = 0000 
var_dump(searchFunction("0000 ma2p")); // false

答案 1 :(得分:0)

如果您可以搜索前两个示例,那么对于任何输入只需删除空格

$string = preg_replace('/\s+/', '', $string);

并小写输入

$string = strtolower($string);

它也会处理其他边缘情况。