繁体   English   中英

检查网址是否与模式匹配

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM