extract filename between last slash and question mark

别说谁变了你拦得住时间么 提交于 2021-02-17 04:45:20

问题


I want to extract filename between last slash and question mark using regex I read some related answers

([^/]*$)

But i have several domain names so i want to extract filename of specific names and looking for a regex that work for all domains. How can i limit it to certain domains? My target is to replace the domain name,

http://old.domain.com/asda/dsdasd/fsdfd/bvc/filename.mp4?fdgfsdgfgfsgf
http://new.domain.com/filename.mp4

Sincerely


回答1:


You could try

preg_replace('/(.*:\/\/).*\/(.*?)(\?.*|$)/', '$1new.domain.com/$2', $url );

replacing the full domain and path with the new one.

See it here at Ideone.

Edit:

Or if you really need to extract the filename (as you say in the question) try

preg_match('/[^\/]+?(?=\?|$)/', $url, $matches);

as showed here.




回答2:


For your this specific problem use this solution or please elaborate your question with example

<?php
$url = 'http://old.domain.com/asda/dsdasd/fsdfd/bvc/filename.mp4?fdgfsdgfgfsgf';
//var_dump(parse_url($url));

$scheme= parse_url($url, PHP_URL_SCHEME);   // http
$host = parse_url($url, PHP_URL_HOST);   //old.domain.com
$path = parse_url($url, PHP_URL_PATH);  //asda/dsdasd/fsdfd/bvc
$filename = basename($path); //filename.mp4
echo $newUrl = $scheme.'//new.domain.com/'.$filename;
?>

output

http//new.domain.com/filename.mp4

for more info about parse_url Please read http://php.net/manual/en/function.parse-url.php



来源:https://stackoverflow.com/questions/38887570/extract-filename-between-last-slash-and-question-mark

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!