2019-05-21 07:46
浏览 271


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

  $paths = [

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?

图片转代码服务由CSDN问答提供 功能建议

我有一个由正则表达式字符串组成的路径数组:</ p>

 < 代码> $ paths = [
'/ cars $',
'。* \ / cars $',
'^ cars \ /.*/',
'/ trucks $',
'。*  \ / trucks $',
 </ code> </ pre> 

我想检查当前路径是否与该数组中的内容匹配,例如:</ p> \ n

  if(in_array($ current_path,$ paths)){
 </ code> </ pre> 

所以例如,如果 我的网址是 some-site.com/cars </ code>或 some-site.com/cars/honda </ code>,然后我想在if语句中返回一些内容。</ p> \ n

但我无法弄清楚如何使用正则表达式。</ p>

我使用 preg_grep()</ code>进行了调查,但这似乎只能起作用 一次使用一组正则表达式规则。</ p>

我可以使用 preg_match </ code>和一个字符串,例如:</ p>

  $ paths ='/ cars$|.*\/cars$|^cars\/.*/|/trucks$|.*\/trucks$';
nnif(preg_match($ paths)  ,$ current_path)){
} \  n </ code> </ pre> 

但我最终会在此列表中添加许多网址,因此我更愿意使用数组。</ p>

有人知道吗 如果有一个功能可以达到这个目的吗?</ p> </ div>

2条回答 默认 最新

相关推荐 更多相似问题