Musa Muaz
Musa Muaz

Reputation: 714

I want to retrieve the filename without extension from an url with php

I have an url which contains various POST-DATA in it And an image file at last. My link is : http://website-link.com/?page=gf_signature&signature=565dbca63791e5.87676354.png

I want to seperate the 565dbca63791e5.87676354.png from the url and seperate the extension (.png) from it.

I can do it :but it is from only plain URL:

$path = "/home/httpd/html/index.php";
$file = basename($path);         // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"

Upvotes: 0

Views: 181

Answers (3)

Jan
Jan

Reputation: 43169

First of all: use parse_url() as suggested in the comments. If you however opt for a regex solution, consider the following code:

$str = "http://website-link.com/?page=gf_signature&signature=565dbca63791e5.87676354.png";
$regex = "/signature=(?<signature>[^&]+)/";
// that is: match signature= literally, then match everything up to a new ampersand and save it to the group "signature"
preg_match($regex, $str, $matches);
$signature = $matches["signature"];
$ext = substr(strrchr($signature, '.'), 1);

print "Signature: $signature with extension: $ext";
// prints out: Signature: 565dbca63791e5.87676354.png with extension: png

See a working PHP fiddle here.

Upvotes: 0

Koga
Koga

Reputation: 585

$filename = $_REQUEST['signature'];
$pathinfo = pathinfo($filename);

$pathinfo['filename'] will print 565dbca63791e5.87676354 and $pathinfo['extension'] will be png.

Upvotes: 1

Sergey  Belyakov
Sergey Belyakov

Reputation: 159

If i correctly understand you, then you need some function like this

$arr = explode('.', $_REQUEST['signature']);
function arrayFilter($arr){
    foreach($arr as $key=>$item){
        if(!next($arr)){
            $result['extension'] = $item;
        } else {
            $result['value'] .= $item . '.'; 
        }
    }
    $result['value'] = substr($result['value'], 0, -1);
    return $result;
}
$data= arrayFilter($arr);

And will print [value] => 565dbca63791e5.87676354 [extension] => png

Upvotes: 0

Related Questions