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

报告相同问题?

悬赏问题

  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。