w3resource

PHP String Exercises: Extract the file name from the specified string


5. Extract Filename from Path

Write a PHP script to extract the file name from the following string.

Sample String : 'www.example.com/public_html/index.php'

Visual Presentation:

PHP String Exercises: Extract the file name from the specified string

Sample Solution:

PHP Code:

<?php
$path = 'www.example.com/public_html/index.php'; // Assigns a string containing a file path to the variable $path
$file_name = substr(strrchr($path, "/"), 1);     // Finds the last occurrence of '/' in $path and extracts the substring after it
echo $file_name."\n";                            // Outputs the extracted file name "index.php"
?>

Output:

index.php

Explanation:

The above PHP code extracts the file name from a given file path stored in the variable '$path'. It does this by using the "strrchr(") function to find the last occurrence of the '/' character in the path and then using "substr()" to extract the substring after that character. Finally, it echoes the extracted file name.

Flowchart :

Flowchart: Extract the file name from the specified string

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract the file name with extension from a given full URL string using basename().
  • Write a PHP function that retrieves the filename from a path and then strips the extension before returning the base name.
  • Write a PHP program to parse a file path and output both the file name and its extension separately.
  • Write a PHP script to handle multiple file paths and return an array containing just the file names from each path.

Go to:


PREV : Convert Variable to String.
NEXT : Extract Username from Email.

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.