w3resource

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

PHP String: Exercise-5 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to convert the value of a PHP variable to string.
Next: Write a PHP script to extract the user name from the specified email ID.

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.