w3resource

PHP String Exercises: Get the filename component of the specified path


13. Extract Filename Component from URL

Write a PHP script to get the filename component of the following path.

Sample path : "https://www.w3resource.com/index.php"

Visual Presentation:

PHP String Exercises: Get the filename component of the specified path

Sample Solution:

PHP Code:

<?php
// Define the path of the file
$path = 'www.example.com/public_html/index.php';

// Extract the filename from the path using the basename() function
// The second argument ".php" specifies the suffix to be removed from the filename
$file = basename($path, ".php");

// Output the extracted filename
echo $file."\n";
?>

Output:

index

Explanation:

In the exercise above,

  • Define Path: It initializes a variable $path with the value 'www.example.com/public_html/index.php', representing the path of a file.
  • Extract Filename: It uses the basename() function to extract the filename from the path specified in $path. The second argument " .php" is passed to specify that if the filename has a .php extension, it should be removed.
  • Output Filename: It prints the extracted filename using echo.

Flowchart :

Flowchart: Get the filename component of the specified path

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract the file name without extension from a given URL using pathinfo().
  • Write a PHP function to parse a URL, retrieve the filename part, and then output it without the file extension.
  • Write a PHP program to extract and display only the base name (excluding the extension) from a full URL string.
  • Write a PHP script to split a URL by slashes and then use string manipulation to extract the file name component.

Go to:


PREV : Convert String to Array (Split by New Line).
NEXT : Print Next Character with Wrap-Around.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.