简体   繁体   English

PHP在字符串数组中查找子字符串

[英]PHP Find Substring inside String Array

I have the following array: 我有以下数组:

$historicalFullList = ['Fecha','H-kWH-Total','H-kWH-Pico','H-kWH-Resto','H-kWH-Valle','H-Acum-Pico','H-Acum-Resto','H-Acum-Valle','H-Fecha-Pico','H-Fecha-Resto','H-Fecha-Valle','H-kW-Pico','H-kW-Resto','H-kW-Valle','H-kVARH-Total','error','factMult','H-kW-Pico-C','H-kW-Resto-C','H-kW-Valle-C'];

I want to create a function to find if the substring 'Hk' exists in the array. 我想创建一个函数来查找数组中是否存在子字符串“ Hk”。 (in this example array it should return TRUE) (在此示例数组中,它应该返回TRUE)

For some reason the following code doesn't work. 由于某些原因,以下代码无法正常工作。 Is there a better way to do this? 有一个更好的方法吗?

function test($substring, $array){

    foreach ($array as $item){
        if (strpos($substring, $item)!== false){
            return true;
        }else{
            return false;
        }
    }
}

then called it.. 然后叫它..

if (test('H-k',$historicalFullList)){
    do stuff...
}

move your return false out of the foreach, else it will return false after the first comparison if it doesn't contain $substr . 将您的return false移出foreach,否则,如果第一次比较后不包含$substr ,它将返回false。

function test($substring, $array){
    foreach ($array as $item){
        if (strpos($item,$substring)!== false){
            return true;
        }
    }
    return false;       
}

Also, swap the needle and the haystack for strpos. 另外,将针头和干草堆换成草皮。

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

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