簡體   English   中英

如何使用PHP來獲取文件名?

[英]How do I use PHP to grab the name of the file?

我想做的是PHP查看URL並僅獲取文件名,而無需我輸入路徑或任何內容(無論如何都是動態的)。 例如

http://google.com/info/hello.php ,我想獲取“ hello”位。

救命?

謝謝。

$filename = __FILE__;

現在,您可以將其拆分為點,例如

$filenameChunks = split(".", $filename);

$nameOfFileWithoutDotPHP = $filenameChunks[0];

您需要basenameexplode才能獲得不帶擴展名的名稱:

$name = basename($_SERVER['REQUEST_URI']);
$name_array = explode('.', $name);
echo $name_array[0];

這是輕松獲取文件名而無需擴展名的安全方法

$info = pathinfo(__FILE__);
$filename = $info['filename'];

$_SERVER['REQUEST_URI']包含請求的URI路徑和查詢。 然后,您可以使用parse_url獲取路徑,並使用basename僅獲取文件名:

basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php')

http://php.net/manual/zh/function.basename.php

$file = basename(__FILE__); // hello.php
$file = explode('.',$file); // array
unset($file[count($file)-1]); // unset array key that has file extension
$file = implode('.',$file); // implode the pieces back together
echo $file; // hello

您可以將parse_urlpathinfo結合使用

這是一個例子

$parseResult = parse_url('http://google.com/info/hello.php');
$result = pathinfo($parseResult['path'], PATHINFO_FILENAME);

$result將包含“ hello”

有關功能的更多信息,請參見: parse_url pathinfo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM