在 PHP 中搜索字符串或字符串的一部分 [英] Search for a string or part of string in PHP

查看:43
本文介绍了在 PHP 中搜索字符串或字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

谢谢!

数组包含以下格式的产品":

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 Jacket
        [size] => YS
        [price] => 55
        [group] => Team Clothing
        [id] => 3000-YS
    )

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

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.

推荐答案

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

array_filter lets 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:

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));
});

这篇关于在 PHP 中搜索字符串或字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆