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

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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 关于#python##pyqt#的问题,如何解决?
      • ¥15 html+css网页设计 html+css网页设计
      • ¥15 用html加css制作一个网页
      • ¥200 MFC中如何对ListCtrl的某一列的文本能换行显示
      • ¥15 clion添加库文件
      • ¥15 ERROR C2143怎么出现的?为什么ERROR C2144会这么转移,它是怎么出现的?该怎么解决?
      • ¥15 华大的hc32l136外部中断引脚怎么设置
      • ¥15 这个问题如何解答,需要答案
      • ¥15 ubuntu18.04 tty报错&tty界面su/sudo命令无法执行,如何解决?
      • ¥20 下面的压缩方法是否可行