如何匹配可以以查询字符串结尾的 url 中的文件扩展名?

Posted

技术标签:

【中文标题】如何匹配可以以查询字符串结尾的 url 中的文件扩展名?【英文标题】:How match file extension in url that can end with querystring? 【发布时间】:2014-11-09 14:40:43 【问题描述】:

我想匹配以下所有 URL 中的文件扩展名直到问号。所以 URL #4 将匹配“file.pdf”中的 pdf,但不匹配“otherfile.exe”中的“exe”。

http://www.someplace.com/directory/file.pdf
http://www.someplace.com/directory/file.pdf?otherstuff=true
http://www.someplace.com/directory/file.pdf?other=true&more=false
http://www.someplace.com/directory/file.pdf?other=true&more=false&value=otherfile.exe

我该怎么做?

我试过了,但它不起作用:

([^\.]+)(\?|[^\?]$)+

【问题讨论】:

你试过用phpparse_url()吗? 我不确定您是否只想知道是否存在匹配项,或者您是否想要字符串中的主机和路径。请说明。 【参考方案1】:

这将是我将使用的版本

/\w+\.[A-Za-z]3,4(?=\?|$)/

这是一个工作版本:

http://regex101.com/r/sY2fR0/1

同时使用前瞻?或者字符串的结尾(?=\?|$) 然后你可以匹配它后面的内容。

$re = "/\\w+\\.[A-Za-z]3,4(?=\\?|$)/"; 
$str = "http://www.someplace.com/directory/file.pdf?other=true&more=false&value=otherfile.exe\n\n"; 

preg_match($re, $str, $matches);

【讨论】:

不幸的是,它从“。”的太早开始匹配。在这种情况下:http://www.com.com/something/sampson.masterplan.pdf?sdf 它将匹配“masterplan.pdf”有没有办法解决这个问题? (另外,我添加了0-9,所以它可以匹配mp3) 我稍微改成了:/\w+\.([A-Za-z0-9]3,4)(?=\?|$)/【参考方案2】:

为了匹配,试试这个不区分大小写的函数:

function matchURLs($desiredURL, $compareURL)
  $url = parse_url($compareURL);
  if(preg_match('/^'$url['scheme'].'://'.$url['host'].$url['path'].'$/i', $desiredURL))
    return true;
  
  return false;

matchURLs('http://www.someplace.com/directory/file.pdf', 'http://www.someplace.com/directory/file.exe'); // false
matchURLs('http://www.someplace.com/directory/file.pdf', 'http://www.someplace.com/directory/file.pdf?value=file.exe'); // true

要获得?之前的:

function URL_before_query($url)
  $u = parse_url($url);
  return $u['scheme'].'://'.$u['host'].$u['path'];

echo URL_before_query('http://www.someplace.com/directory/file.pdf?other=true&more=false&value=otherfile.exe'); // http://www.someplace.com/directory/file.pdf

【讨论】:

【参考方案3】:
<?
$str = '
http://www.someplace.com/directory/file1.pdf
http://www.someplace.com/directory/file2.pdf?otherstuff=true 
http://www.someplace.com/directory/file3.pdf?other=true&more=false 
http://www.someplace.com/directory/file4.pdf?other=true&more=false&value=otherfile.exe
';
$regex= '~.*/\K[^?\n]+~';

preg_match_all($regex, $str, $out, PREG_SET_ORDER);
print_r($out);
?>

输出

Array ( 
   [0] => Array ( 
                 [0] => file1.pdf 
                ) 
   [1] => Array ( 
                 [0] => file2.pdf 
                ) 
   [2] => Array ( 
                 [0] => file3.pdf 
                ) 
   [3] => Array ( 
                 [0] => file4.pdf 
                 ) 
  ) 

【讨论】:

以上是关于如何匹配可以以查询字符串结尾的 url 中的文件扩展名?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用正则表达式匹配不以某些字符开头或结尾的单词?

正则表达式以啥结尾

正则表达式:如何匹配以括号“)”结尾的单词

MySQL REGEXP:正则表达式查询

tomcat

如何使用 JavaScript 匹配我所在窗口的当前 URL 中的字符串?