簡體   English   中英

Php preg_match使用URL作為正則表達式

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM