PHP:获取与另一个字符串数组的子字符串匹配的字符串数组的数组值 [英] PHP: Get array values of a string array that match substrings of another string array

查看:173
本文介绍了PHP:获取与另一个字符串数组的子字符串匹配的字符串数组的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个数组:

$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');

我想得到一个包含所有与子字符串匹配的字符串的数组:

I want to get an array which contains all the strings, that match the substrings:

Array
(
    [0] => Apple
    [2] => Orange
)

或具有新索引:

Array
(
    [0] => Apple
    [1] => Orange
)

推荐答案

想到的一个简单解决方案:结合 array_filter strpos ;

A simple solution that comes to mind: combine array_filter and strpos;

$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');

$result = array_filter($strings, function($item) use($substrings) {
  foreach($substrings as $substring)
    if(strpos($item, $substring) !== FALSE) return TRUE;
  return FALSE;
});

要重置索引,可以使用 array_values 函数.

To reset indices, you can use the array_values function.

这篇关于PHP:获取与另一个字符串数组的子字符串匹配的字符串数组的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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