doukui9491 2014-02-24 18:23
浏览 19
已采纳

查找用户搜索是否在任何数组字段的一部分内

I'm trying to figure out a way to see if user entered search term relates to anything in the $propertyData array.

So far I have used in_array() function, but to my understanding it will only match if user entered search term matches array field exactly e.g. User entered "This is a house" and it matches first field in an array wich is "This is a house", but if user enters "This is a" or "a house" it will not match, even though these words are present in that field.

if(in_array($getSearch, $propertyData)) {
   // $getSearch is user input
   // $propertyData is array containing fields
}

Is there a function / way that can be used to achieve a task?

  • 写回答

4条回答 默认 最新

  • doujuanqi2909 2014-02-24 18:27
    关注

    Try preg_grep(). It searches an array by regular expression and returns an array of values that matched the expression. So if anything other than an empty array is returned it is considered true:

    if(preg_grep("/$getSearch/", $propertyData)) {
    

    For case insensitive add the i modifier:

    if(preg_grep("/$getSearch/i", $propertyData)) {
    

    If you want an array of all of the values that matched (if more than 1) also, then:

    if($matches = preg_grep("/$getSearch/i", $propertyData)) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?