2017-10-12 17 views
3

我有網址腓的preg_match使用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/(.*)'作爲正則表達式。

歸檔的最佳方式是什麼?

回答

1

preg_grep()提供的代碼較短線,但因爲要匹配的子串不出現有任何變量字符它,最好的做法將指示strpos()更適合。

代碼:(Demo

$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的網址。這與你問題中的細節一致。

使用strpos()

  • 檢查strpos()===0意味着該子必須在字符串的開頭找到。
  • 這將允許字符串末尾的任何結尾字符。
0

我認爲你需要使用preg_grep,因爲你有網址 的陣列,這將返回匹配的網址您的病情

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

的數組,你也可以使用validate filters在PHP中驗證網址

0

您需要避開正斜槓和週期才能獲得http:\/\/www\.example\.com\/eng-gb\/products\/(.*)。之後,您可以直接放置網址。

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

實施例:

$matches = array(); 
preg_match('/\/eng-gb\/products\/(.*)/', $your_url, $matches); 
$product = $matches[1];