如何使用 preg_match 在数组中搜索? [英] How to search in an array with preg_match?

查看:42
本文介绍了如何使用 preg_match 在数组中搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I search in an array with preg_match?

示例:

<?php
if( preg_match( '/(my\n+string\n+)/i' , array( 'file' , 'my string  => name', 'this') , $match) )
{
    //Excelent!!
    $items[] = $match[1];
} else {
    //Ups! not found!
}
?>

推荐答案

在这篇文章中,我将为您提供三种不同的方法来完成您的要求.我实际上建议使用最后一个片段,因为它最容易理解,而且代码也非常简洁.

有一个专门用于此目的的函数,preg_grep.它将接受一个正则表达式作为第一个参数,一个数组作为第二个参数.

There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.

看下面的例子:

$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
)

文档

  • PHP:preg_grep - 手册
  • array_reducepreg_match 可以干净利落地解决这个问题;请参阅下面的片段.

    array_reduce with preg_match can solve this issue in clean manner; see the snippet below.

    $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_*preg_* 函数,但它实际上更简洁.

    Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_* or preg_* function.

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

    Wrap it in a function if you are going to use this method more than once.

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

    文档

    这篇关于如何使用 preg_match 在数组中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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