drtzb06222 2019-05-21 07:46
浏览 286
已采纳

PHP:如何在in_array中使用正则表达式字符串数组?

I have an array of paths that consist of regex strings:

  $paths = [
    '/cars$',
    '.*\/cars$',
    '^cars\/.*/',
    '/trucks$',
    '.*\/trucks$',
  ];

I want to check if my current path matches something in that array, eg:

if (in_array($current_path, $paths)) {
  //Do something
}

So for example, if my URL is some-site.com/cars or some-site.com/cars/honda then I want to return something in the if statement.

But I cannot figure out how to get this working with the regex.

I investigated using preg_grep() but that seems to only work with one set of regex rules at a time.

I can get this to work with preg_match and a string, eg:

$paths = '/cars$|.*\/cars$|^cars\/.*/|/trucks$|.*\/trucks$';

if (preg_match($paths, $current_path)) {
  //Do something
}

But I will eventually have many URLs added to this list so I would prefer to use an array.

Would anyone know if there is a function that achieves this?

  • 写回答

2条回答 默认 最新

  • duanganleng0577 2019-05-21 08:52
    关注

    If you want to know, what patterns of an array match the string, how about using array_filter.

    $res = array_filter($paths, function ($v) USE ($url) {
      return preg_match('~'.$v.'~', $url);
    });
    

    See PHP demo at 3v4l.org

    echo count($res)." patterns matched:
    "; print_r($res);
    

    2 patterns matched: Array ( [0] => /cars$ 1 => .*/cars$ )

    Used ~ as pattern delimiter, so you wouldn't need to escape all those url slashes.

    Be aware, that .*/cars$ looks redundant, if you already match for /cars$.


    If you want to break on first match, use foreach which is probably more efficient (demo).

    foreach($paths AS $v) {
      if (preg_match('~'.$v.'~', $url)) {
        echo $v.' matched'; break;
      }
    }
    

    You can further easily display the matched part of $url by using $out of preg_match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料