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:
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 :
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/php-string-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics