w3resource

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

PHP String: Exercise-13 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to put a string in an array.
Next: Write a PHP script to print the next character of a specific character.

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.