[英]Php preg_match using URL as regex
我有一系列的網址
[
'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/(.*)
在這種情況下,我需要排除'about-us'。
我還需要使用'http://www.example.com/eng-gb/products/(.*)'
作為正則表達式。
歸檔的最佳方式?
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;}));
輸出:
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_grep()
:
.com
的點。 /products/
但不是/products
結尾的url。 這與您問題中的詳細信息一致。 使用strpos()
:
strpos()===0
意味着必須在字符串的開頭找到子字符串。 我認為你需要使用preg_grep,因為你有一些url數組,這將返回符合你條件的url數組
$matches = preg_grep('/products\\/.*$/', $urls);
並且您還可以在php中使用驗證過濾器來驗證網址
您需要轉義正斜杠和句點才能獲得http:\\/\\/www\\.example\\.com\\/eng-gb\\/products\\/(.*)
。 之后,您可以直接放置URL。
或者(更好)是搜索\\/eng-gb\\/products\\/(.*)
。
例:
$matches = array();
preg_match('/\/eng-gb\/products\/(.*)/', $your_url, $matches);
$product = $matches[1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.