PHP Instance code to get the file name through the file path

  • 2021-11-10 08:59:53
  • OfStack

Physical interception


$file = '/www/htdocs/inc/lib.inc.php';

$filename = basename($file);

echo $filename, '<br/>';// lib.inc.php

$filename = str_replace(strrchr($filename, '.'), '', $filename);

echo $filename, '<br/>';// lib.inc

Use pathinfo ($path, $options)


$file = '/www/htdocs/inc/lib.inc.php';

$path_parts = pathinfo($file);

echo ' Directory name ' . $path_parts['dirname'], '<br/>'; // /www/htdocs/inc

echo ' Full name of file ' . $path_parts['basename'], '<br/>'; // lib.inc.php

echo ' File suffix ' . $path_parts['extension'], '<br/>';// php

echo ' File name ' . $path_parts['filename'], '<br/>'; // lib.inc  // PHP >= 5.2.0

echo ' Directory name ' . pathinfo($file, PATHINFO_DIRNAME), '<br/>'; // /www/htdocs/inc

echo ' Full name of file ' . pathinfo($file, PATHINFO_BASENAME), '<br/>'; // lib.inc.php

echo ' File suffix ' . pathinfo($file, PATHINFO_EXTENSION), '<br/>';// php

echo ' File name ' . pathinfo($file, PATHINFO_FILENAME), '<br/>'; // lib.inc  // PHP >= 5.2.0

The method is very simple, we can test in the local, thank you for the support of this site, more content waiting for you to learn.


Related articles: