问题
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