PHP使用preg_match或regex作为array_search的值或array_keys_exist的键 [英] PHP using preg_match or regex as value for array_search or the key for array_keys_exist

查看:61
本文介绍了PHP使用preg_match或regex作为array_search的值或array_keys_exist的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 array_seach() array_keys_exist 中使用正则表达式或 preg_match()吗?

I was wondering if it was possible to use regex or preg_match() in array_seach() or array_keys_exist?

即. array_keys_exist($ array,"^ \ d + $")匹配所有纯数字字符的键

ie. array_keys_exist($array,"^\d+$") to match all keys that are solely numeric characters

推荐答案

我不知道它是否完全适合您的需求,但是您应该看看 array_keys 的返回值使用 preg_grep 对键进行相同的操作代码> .

I don't know whether it suits your needs exactly, but you should have a look at the preg_grep function, which will check an array of strings against a regex and return all matching array elements. You could do same with the keys, by using preg_grep on the return value of array_keys.

这与 array_search / array_key_exists 不同,它们在找到匹配项后停止,因为可能只有一个匹配项.另一方面,使用正则表达式时,可能有许多满足条件的元素,因此 preg_grep 将返回所有元素.

This is different from array_search / array_key_exists in the respect, that these stop after they have found a match, because there may only be one match. With regex on the other hand there may be many elements satisfying the condition, so preg_grep will return all of them.

这篇关于PHP使用preg_match或regex作为array_search的值或array_keys_exist的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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