[英]checking if an URL matching with a pattern
我有一個代碼可以從網站上獲取模式列表: https : //noembed.com/providers
使用以下代碼,我可以顯示所有模式:
$supported = 'https://noembed.com/providers' ;
$jsonSUPP = json_decode(file_get_contents($supported),true) ;
echo 'pour:'.$url.'<br/>' ;
foreach ($jsonSUPP as $key => $value) {
foreach ($value[patterns] as $ent) {
echo "**patt : $ent <br />\n" ;
}
}
現在我想創建一個條件:如果$ url與$ ent匹配,則...我嘗試使用preg_match
但出現錯誤。 還有ereg
請問你能幫幫我嗎
嘗試使用preg_quote,以便在URL中轉義斜線:
if(preg_match('/' . preg_quote($url) . '/', $ent))
return true;
或更改定界符:
if(preg_match('%' . $url . '%', $ent))
return true
您需要使用定界符包裝正則表達式-我在下面使用(
和)
:
<?php
$url = "http://en.wikipedia.org/wiki/Error";
$supported = 'https://noembed.com/providers' ;
$jsonSUPP = json_decode(file_get_contents($supported),true) ;
echo 'pour:'.$url."<br/>\n" ;
$match = NULL;
foreach ($jsonSUPP as $key => $value) {
foreach ($value['patterns'] as $ent) {
if (preg_match("(".$ent.")",$url)) {
$match = $key;
break;
}
//echo "**patt : $ent <br />\n" ;
}
if ($match !== NULL) {
break;
}
}
if ($match) {
echo "$url matched $match ({$jsonSUPP[$match]['name']}): \n";
print_r($jsonSUPP[$match]);
}
輸出:
pour:http://en.wikipedia.org/wiki/Error<br/>
http://en.wikipedia.org/wiki/Error matched 3 (Wikipedia):
Array (
[patterns] => Array
(
[0] => http://[^\.]+\.wikipedia\.org/wiki/.*
)
[name] => Wikipedia
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.