[英]Php preg_match using URL as regex
i have an array of urls 我有一系列的网址
[
'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',
]
I need to write a regex for filter only the ones end with: 我需要为过滤器编写一个正则表达式,只有以下结尾:
http://www.example.com/eng-gb/products/(.*)
in this case i need to exclude 'about-us'. 在这种情况下,我需要排除'about-us'。
I need also use 'http://www.example.com/eng-gb/products/(.*)'
as regex. 我还需要使用
'http://www.example.com/eng-gb/products/(.*)'
作为正则表达式。
The best way for archive? 归档的最佳方式?
preg_grep()
provides a shorter line of code, but because the substring to be matched doesn't appear to have any variable characters in it, best practice would indicate strpos()
is better suited. preg_grep()
提供了一个较短的代码行,但由于要匹配的子字符串似乎没有任何变量字符,因此最佳实践表明strpos()
更适合。
$urls=[
'http://www.example.com/eng-gb/products/test-1',
'http://www.example.com/eng-gb/badproducts/test-2',
'http://www.example.com/eng-gb/products/test-3',
'http://www.example.com/eng-gb/badproducts/products/test-4',
'http://www.example.com/products/test-5',
'http://www.example.com/eng-gb/about-us',
];
var_export(preg_grep('~^http://www.example\.com/eng-gb/products/[^/]*$~',$urls));
echo "\n\n";
var_export(array_filter($urls,function($v){return strpos($v,'http://www.example.com/eng-gb/products/')===0;}));
Output: 输出:
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',
)
Some notes: 一些说明:
Using preg_grep()
: 使用
preg_grep()
:
.com
. .com
的点。 /products/
but not /products
. /products/
但不是/products
结尾的url。 This is in accordance with the details in your question. Using strpos()
: 使用
strpos()
:
strpos()===0
means that the substring must be found at the start of the string. strpos()===0
意味着必须在字符串的开头找到子字符串。 I think you need use preg_grep cause you have array of urls and this will return array of url that match your condition 我认为你需要使用preg_grep,因为你有一些url数组,这将返回符合你条件的url数组
$matches = preg_grep('/products\\/.*$/', $urls);
and also you can use validate filters in php to validate urls 并且您还可以在php中使用验证过滤器来验证网址
You'll need to escape the forward slashes and periods to get http:\\/\\/www\\.example\\.com\\/eng-gb\\/products\\/(.*)
. 您需要转义正斜杠和句点才能获得
http:\\/\\/www\\.example\\.com\\/eng-gb\\/products\\/(.*)
。 After that, you could just place the URL in directly. 之后,您可以直接放置URL。
Alternatively (better) would be to search for \\/eng-gb\\/products\\/(.*)
. 或者(更好)是搜索
\\/eng-gb\\/products\\/(.*)
。
Example: 例:
$matches = array();
preg_match('/\/eng-gb\/products\/(.*)/', $your_url, $matches);
$product = $matches[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.