Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用URL作为正则表达式的Php预匹配_Php_Regex - Fatal编程技术网

使用URL作为正则表达式的Php预匹配

使用URL作为正则表达式的Php预匹配,php,regex,Php,Regex,我有一个URL数组 [ 'http://www.example.com/eng-gb/products/test-1', 'http://www.example.com/eng-gb/products/test-3', 'http://www.example.com/eng-gb/about-us', ] 我需要为过滤器编写一个正则表达式,仅以以下结尾的过滤器: http://www.example.com/eng-gb/products/(.*) 在这种情况下,我需要排除“关于

我有一个URL数组

[
  'http://www.example.com/eng-gb/products/test-1',
  'http://www.example.com/eng-gb/products/test-3',
  'http://www.example.com/eng-gb/about-us',
]
我需要为过滤器编写一个正则表达式,仅以以下结尾的过滤器:

http://www.example.com/eng-gb/products/(.*)
在这种情况下,我需要排除“关于我们”

我还需要使用
'http://www.example.com/eng-gb/products/(.*)
作为正则表达式

存档的最佳方式?

我认为您需要使用,因为您有一系列URL 这将返回符合您的条件的url数组

$matches=preg_grep('/products\/.*$/',$url)


您还可以在php中使用来验证URL

您需要避开正斜杠和句点才能获得
http:\/\/www\.example\.com\/eng gb\/products\/(.*)
。之后,您可以直接将URL放入

或者(更好)搜索
\/eng gb\/products\/(.*)

例如:

$matches = array();
preg_match('/\/eng-gb\/products\/(.*)/', $your_url, $matches);
$product = $matches[1];
preg_grep()
提供了一行较短的代码,但由于要匹配的子字符串中似乎没有任何可变字符,因此最佳实践表明
strps()
更适合

代码:()

输出:

array (
  0 => 'http://www.example.com/eng-gb/products/test-1',
  2 => 'http://www.example.com/eng-gb/products/test-3',
)

array (
  0 => 'http://www.example.com/eng-gb/products/test-1',
  2 => 'http://www.example.com/eng-gb/products/test-3',
)
一些注意事项:

使用
preg\u grep()

  • 使用非斜线模式分隔符,这样就不必转义模式中的所有斜线
  • .com
    上转义点
  • 编写完整的域和目录路径,包括开始和结束锚,以进行最严格的验证
  • 在模式末尾附近使用一个否定字符类,以确保不添加其他目录(当然,除非您希望包含所有子目录)
  • 我的模式将匹配以
    /products/
    结尾的url,但不匹配以
    /products
    结尾的url。这与你问题中的细节相符
使用strpos()

  • 检查strpos()==0意味着必须在字符串的开头找到子字符串
  • 这将允许在字符串末尾添加任何尾随字符
array (
  0 => 'http://www.example.com/eng-gb/products/test-1',
  2 => 'http://www.example.com/eng-gb/products/test-3',
)

array (
  0 => 'http://www.example.com/eng-gb/products/test-1',
  2 => 'http://www.example.com/eng-gb/products/test-3',
)