By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Extract File - String Task

+6 votes

Write a program that reads the path to a file and subtracts the file name and its extension.


extract file string task

asked in PHP category by user matthew44

1 Answer

+5 votes

Here is my solution with substr() function in PHP:


$fullFileName = readline();
$lastSlash = strrpos($fullFileName, "\\");//Escape the \
$file = substr($fullFileName, $lastSlash + 1);

//$file = Template.pptx
$lastDot = strrpos($file, ".");
$fileExtension = substr($file, $lastDot + 1);//pptx
$fileName = substr($file, 0, $lastDot);//Template

echo "File name: " . $fileName.PHP_EOL;
echo "File extension: " . $fileExtension;

And some screenshots of some of the string functions in PHP:

find substring php

Here is a link to a video explaining the substr() function:

...and 2 replace functions in PHP:

str replace php

answered by user hues