栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用preg_match在数组中搜索?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用preg_match在数组中搜索?

在这篇文章中,我将为您提供三种不同的方法来满足您的要求。 我实际上建议使用最后一个代码段,因为它最容易理解并且代码简洁。

如何查看数组中与我的正则表达式匹配的元素?

有专门用于此目的的功能

preg_grep
。它将一个正则表达式作为第一个参数,并将一个数组作为第二个参数。

请参见以下示例:

$haystack = array (  'say hello',  'hello stackoverflow',  'hello world',  'foo bar bas');$matches  = preg_grep ('/^hello (w+)/i', $haystack);print_r ($matches);

输出

Array(    [1] => hello stackoverflow    [2] => hello world)

但是我只想获取指定组的值。怎么样?

array_reduce
preg_match
能解决清洁方式这一问题; 请参见下面的代码段。

$haystack = array (  'say hello',  'hello stackoverflow',  'hello world',  'foo bar bas');function _matcher ($m, $str) {  if (preg_match ('/^hello (w+)/i', $str, $matches))    $m[] = $matches[1];  return $m;}// N O T E :// ------------------------------------------------------------------------------// you could specify '_matcher' as an anonymous function directly to// array_reduce though that kind of decreases readability and is therefore// not recommended, but it is possible.$matches = array_reduce ($haystack, '_matcher', array ());print_r ($matches);

输出

Array(    [0] => stackoverflow    [1] => world)

使用
array_reduce
似乎很乏味,不是吗?

是的,这实际上是一个清洁的是,虽然它不涉及使用任何现有

array_*
preg_*
功能。

如果要多次使用此方法,请将其包装在函数中。

$matches = array ();foreach ($haystack as $str)   if (preg_match ('/^hello (w+)/i', $str, $m))    $matches[] = $m[1];


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/443184.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号