简体   繁体   English

检查字符串是否存在于数组元素中

[英]check if string exists in array element

Is there any function that can do what strpos does, but on the elements of an array ? 有什么功能可以执行strpos功能,但是可以在数组的元素上执行? for example I have this array : 例如我有这个数组:

    Array
(
 [0] => a66,b30
 [1] => b30
)

each element of the array can contain a set of strings, separated by commas. 数组的每个元素都可以包含一组字符串,以逗号分隔。

Let's say i'm looking for b30. 假设我正在寻找b30。 I want that function to browse the array and return 0 and 1. can you help please ? 我希望该函数浏览数组并返回0和1。请您提供帮助吗? the function has to do the oppsite of what this function does. 该功能必须与此功能相反。

Try this (not tested) : 试试这个(未测试):

function arraySearch($array, $search) {
    if(!is_array($array)) {
        return 0;
    }
    if(is_array($search) || is_object($search)) {
        return 0;
    }
    foreach($array as $k => $v) {
        if(is_array($v) || is_object($v)) {
            continue;
        }
        if(strpos($v, $search) !== false) {
            return 1;
        }
    }
    return 0;
}

You could also use preg_grep for this. 您也可以preg_grep使用preg_grep

<?php

$a = array(
 'j98',
 'a66,b30',
 'b30',
 'something',
 'a40'
);

print_r( count(preg_grep('/(^|,)(b30)(,|$)/', $a)) ? 1 : 0 );

https://eval.in/412598 https://eval.in/412598

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM