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

查看:156
本文介绍了搜索在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一个简单的函数()来检查,如果你的搜索字符串是present:

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

另外,你可以使用一个匿名函数来帮助prevent命名空间的污染:

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

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

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

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