在 PHP 中搜索字符串或部分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5749415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:22:13  来源:igfitidea点击:

Search for a string or part of string in PHP

phparrayssearchstoreproduct

提问by Sahir

I am doing a very small online store application in PHP. So I have an array of maps in PHP. I want to search for a string (a product) in the array. I looked at array_search in PHP and it seems that it only looks for exact match. Do you guys know a better way to do this functionality? Since this is a very small part of what I am actually doing, I was hoping that there was something built in. Any ideas?

我正在用 PHP 做一个非常小的在线商店应用程序。所以我在 PHP 中有一组地图。我想在数组中搜索一个字符串(一个产品)。我在 PHP 中查看了 array_search,它似乎只查找精确匹配。你们知道实现此功能的更好方法吗?由于这只是我实际工作的一小部分,我希望有一些内置的东西。有什么想法吗?

Thanks!

谢谢!

EDIT: The array contains "products" in this format:

编辑:该数组包含以下格式的“产品”:

[6] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [id] => 2000-YM
            )

        [Name] => Team Swim School T-Shirt
        [size] => YM
        [price] => 15
        [group] => Team Clothing
        [id] => 2000-YM
    )

[7] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [id] => 3000-YS
            )

        [Name] => Youth Track Hymanet
        [size] => YS
        [price] => 55
        [group] => Team Clothing
        [id] => 3000-YS
    )

So I was wondering I can do a search such as "Team" and it would return me first item seen here. I am basing the search on the Name (again this is just something small). I understand that I can find the exact string, I am just stuck on the "best results" if it cannot find the exact item. Efficiency is nice but not required since I only have about 50 items so even if I use a "slow" algorithm it won't take much time.

所以我想知道我可以做一个搜索,比如“团队”,它会返回我在这里看到的第一个项目。我基于名称进行搜索(同样,这只是一些小事)。我知道我可以找到确切的字符串,如果找不到确切的项目,我只是停留在“最佳结果”上。效率很好,但不是必需的,因为我只有大约 50 个项目,所以即使我使用“慢”算法也不会花费太多时间。

回答by Marc B

array_filterlets you specify a custom function to do the searching. In your case, a simple function that uses strpos()to check if your search string is present:

array_filter允许您指定一个自定义函数来进行搜索。在您的情况下,一个简单的函数strpos()用于检查您的搜索字符串是否存在:

function my_search($haystack) {
    $needle = 'value to search for';
    return(strpos($haystack, $needle)); // or stripos() if you want case-insensitive searching.
}

$matches = array_filter($your_array, 'my_search');

Alternatively, you could use an anonymous function to help prevent namespace contamination:

或者,您可以使用匿名函数来帮助防止命名空间污染:

$matches = array_filter($your_array, function ($haystack) use ($needle) {
    return(strpos($haystack, $needle));
});

回答by Headshota

foreach($array as $item){
  if(strpos($item,"mysearchword")!== false){
    echo 'found';
  }
}

or you can use preg_match for more flexible search instead of strpos.

或者您可以使用 preg_match 代替 strpos 进行更灵活的搜索。

回答by Kit Ramos

I think Marc B's answer was a good starting point but for me it had some problems. Such as you have to know what the Needle is at "compile time" because you can't dynamically change that value. also if the needle appeared at the start of the string element it would act like it's not there at all. so after a little experimenting I manged to come up with a way around both problems. so you don't have to create a new function for every different needle your going to want to use anymore.

我认为 Marc B 的回答是一个很好的起点,但对我来说它有一些问题。例如,您必须在“编译时”知道 Needle 是什么,因为您无法动态更改该值。此外,如果针出现在字符串元素的开头,它会表现得好像根本不存在。所以经过一些实验后,我设法想出了解决这两个问题的方法。因此,您不必再为要使用的每个不同的针创建新功能。

function my_search($haystack)
{
    global $needle;
    if( strpos($haystack, $needle) === false) {return false;} else {return true;}
}

and it would be called like this:

它会被这样调用:

$needle="item to search for";
$matches = array_filter($my_array, 'my_search');

and being as needle is now accessible in the same scope that the rest of the code is you can set needle to any other string variable you wanted, including user input.

并且作为needle现在可以在与其余代码相同的范围内访问,您可以将need设置为您想要的任何其他字符串变量,包括用户输入。

回答by Homer6

Unfortunately, search is one of the more difficult things to do in computer science. If you build for search based on literal string matches or regular expressions (regex), you may find that you'll be unhappy with the relevance of the results that are returned.

不幸的是,搜索是计算机科学中比较困难的事情之一。如果您基于文字字符串匹配或正则表达式 (regex) 构建搜索,您可能会发现您对返回结果的相关性不满意。

If you're interested in rolling up your sleeves and getting a little dirty with a more sophisticated solution, I'd try Zend's Lucene implementation ( http://framework.zend.com/manual/en/zend.search.lucene.html). I've implemented a search on a site with it. It took a few days, but the results were MUCH better than the 15 minute solution of literal string matching.

如果您有兴趣卷起袖子并使用更复杂的解决方案弄脏一点,我会尝试 Zend 的 Lucene 实现(http://framework.zend.com/manual/en/zend.search.lucene.html)。我已经用它在一个网站上进行了搜索。花了几天时间,但结果比文字字符串匹配的 15 分钟解决方案要好得多。

Let me know if you'd like more info.

如果您想了解更多信息,请告诉我。

Best of luck!

祝你好运!

PS. Here's an example: http://devzone.zend.com/article/91

附注。这是一个例子:http: //devzone.zend.com/article/91

回答by sdolgy

iterate through the array and use substr if you want partial matches:

如果需要部分匹配,请遍历数组并使用 substr:

http://php.net/manual/en/function.substr.php

http://php.net/manual/en/function.substr.php

this should be sufficient if you have a "small" store...

如果您有一家“小”商店,这应该就足够了……

回答by ufucuk

You can user regular expressions on each and every array element like

您可以在每个数组元素上使用正则表达式,例如

foreach($array as $value)
{
    //... your search statement for $value
}

回答by Omkar

I have same Issue but i have created i function to search in array by passing the array, key and value.

我有同样的问题,但我创建了 i 函数来通过传递数组、键和值来搜索数组。

public function searchinarr($array, $key, $value)
{
       $results = array();
            for($i=0;$i<count($array);$i++)
            {
                foreach($array[$i] as $k=>$val)
                {
                    if($k==$key)
                    {
                        if(strpos($val,$value)!== false)
                        {
                            $results[] = $array[$i];
                        }
                    }
                }

            }
            return $results;
}