检查部分匹配阵列(PHP) [英] Check array for partial match (PHP)

查看:98
本文介绍了检查部分匹配阵列(PHP)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有文件名的数组,我需要核对一个code,例如:

 阵列(120_120_435645.jpg,150_150_312312.jpg,250_250_1232327.jpg);

字符串为312312,所以因为它包含字符串的话将匹配150_150_312312.jpg。
如果有在搜索中的所有没有匹配然后标记的code为失踪人。

我试过in_array但如果它是完全匹配,这似乎任何返回true,不知道是不是array_filter将做到这一点枯萎......

任何意见谢谢...也许是我一直盯着它太长,咖啡可以帮助:)


解决方案

  $文件名=阵列(120_120_435645.jpg,150_150_312312.jpg,250_250_1232327.jpg);
$匹配= preg_grep(/ 312312 /,$文件名);
的print_r($比赛);

输出:

 阵列

    [1] => 150_150_312312.jpg

或者,如果你不想使用正则表达式,你可以简单地使用 strpos 提出这个回答:

 的foreach($文件名作为文件名$){
    如果(strpos($文件名,'312312')!== FALSE){
    回声真;
    }
}

演示!

I have an array of filenames which I need to check against a code, for example

array("120_120_435645.jpg","150_150_312312.jpg","250_250_1232327.jpg");

the string is "312312" so it would match "150_150_312312.jpg" as it contains that string. If there are no matches at all within the search then flag the code as missing.

I tried in_array but this seems to any return true if it is an exact match, don't know if array_filter will do it wither...

Thanks for any advice...perhaps I have been staring at it too long and a coffee may help :)

解决方案

$filenames = array("120_120_435645.jpg","150_150_312312.jpg","250_250_1232327.jpg");
$matches = preg_grep("/312312/", $filenames);
print_r($matches);

Output:

Array
(
    [1] => 150_150_312312.jpg
)

Or, if you don't want to use regex, you can simply use strpos as suggested in this answer:

foreach ($filenames as $filename) {
    if (strpos($filename,'312312') !== false) {
    echo 'True';
    }
}

Demo!

这篇关于检查部分匹配阵列(PHP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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