检查URL是否与模式匹配


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,但我有一个错误。

你能帮我一下吗

尝试使用preg_quote so转义url中的斜杠:

if(preg_match('/' . preg_quote($url) . '/', $ent))
   return true;

或更改分隔符:

if(preg_match('%' . $url . '%', $ent))
   return true

您需要用分隔符包装regexp -我在下面使用():

<?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 
)