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

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?