且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-21 18:51:23

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