[英]PHP regex extract url with pattern from string
我有很多關於從字符串中提取所有 url 和檢測具有特定模式的 url 的主題。 但不是兩者。 對不起,我在正則表達式中有點粗糙。 有人可以幫忙嗎?
這是我想要的:
$str = <<<EOF
This string is valid - http://example.com/products/1
This string is not valid - http://example.com/order/1
EOF;
基本上我想提取$str
變量中的所有 url,它有一個帶有/products/
的模式
我為 url 提取嘗試了這個 - /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|:,.;;]*[-a-z0-9+&@#\/%=~_|]/i
但除此之外我只想要那些具有該模式而不是其他模式的人。
您可以使用相同的可選字符 class 在匹配/products/
之前和之后重復所有允許的字符。由於字符 class 很長,您可以通過將其包裝在捕獲組中來縮短符號並將第一個子模式遞歸為(?1)
請注意,您不必使用不同的分隔符來轉義正斜杠。
$re = '`\b(?:(?:https?|ftp)://|www\.)([-a-z0-9+&@#/%?=~_|!:,.;]*)/products/(?1)[-a-z0-9+&@#/%=~_|]`';
$str = <<<EOF
http://example.com/products/1/abc
This string is valid - http://example.com/products/1
This string is not valid - http://example.com/order/1
EOF;
preg_match_all($re, $str, $matches);
print_r($matches[0]);
Output
Array
(
[0] => http://example.com/products/1/abc
[1] => http://example.com/products/1
)
除了“第四只鳥”的答案之外,我提出了另一種混合解決方案,它同時使用正則表達式和經典字符串操作來為 helper function 提供一些額外的選項,例如在運行時獲得不同的結果而不改變 RE
<?php
function GetURL($str, $pattern='/products/')
{
$temp = array();
preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $str, $match);
foreach ($match[0] as $link)
{
if(!$pattern)
array_push($temp, $link);
else if(strpos($link, $pattern) !== false)
array_push($temp, $link);
}
return $temp;
}
$str = <<<EOF
This string is valid - http://example.com/products/1
This string is not valid - http://example.com/order/1
EOF;
print_r(GetURL($str)); //Urls only with /products/ inside
print_r(GetURL($str, '/order/')); //Urls only with /order/ inside
print_r(GetURL($str, false)); //All urls
?>
OUTPUT
Array ( [0] => http://example.com/products/1 )
Array ( [0] => http://example.com/order/1 )
Array (
[0] => http://example.com/products/1
[1] => http://example.com/order/1
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.