php - Regex to extract file extension from URL -
i looking regex match .js
in next uri:
/foo/bar/file.js?cache_key=123
i'm writing function tries identify kind of file beingness passed in parameter. in case, file ends extension .js
, javascript file. i'm working php , preg_match i'm assuming pcre compatible regular expression. i'll build on look , able check multiple file types beingness passed in uri isn't limited js, perhaps css, images, etc.
you can utilize combination of pathinfo
, regular expression. pathinfo
give extension plus ?cache_key=123
, , can remove ?cache_key=123
regex matches ?
, after it:
$url = '/foo/bar/file.js?cache_key=123'; echo preg_replace("#\?.*#", "", pathinfo($url, pathinfo_extension)) . "\n";
output:
js
input:
$url = 'my_style.css?cache_key=123';
output:
css
obviously, if need .
, it's trivial add together file extension string.
eta: if want regex solution, trick:
function parseurl($url) { # takes lastly dot can find , grabs text after echo preg_replace("#(.+)?\.(\w+)(\?.+)?#", "$2", $url) . "\n"; } parseurl('my_style.css'); parseurl('my_style.css?cache=123'); parseurl('/foo/bar/file.js?cache_key=123'); parseurl('/my.dir.name/has/dots/boo.html?cache=123');
output:
css css js html
php regex
No comments:
Post a Comment