简体   繁体   English

我想使用php从URL中检索不带扩展名的文件名

[英]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. 我有一个URL,其中包含各种POST-DATA和一个图像文件。 My link is : http://website-link.com/?page=gf_signature&signature=565dbca63791e5.87676354.png 我的链接是: http://website-link.com/?page=gf_signature&signature=565dbca63791e5.87676354.png : 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. 我想将565dbca63791e5.87676354.png与URL分开,并将扩展名(.png)与URL分开。

I can do it :but it is from only plain URL: 我可以做到的:但是它仅来自纯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"
$filename = $_REQUEST['signature'];
$pathinfo = pathinfo($filename);

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

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 并打印[value] => 565dbca63791e5.87676354 [extension] => png

First of all: use parse_url() as suggested in the comments. 首先:按照注释中的建议使用parse_url() 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 . 在这里查看有效的PHP小提琴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM