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

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.

Examples:

extract file string task

asked in PHP category by user matthew44

1 Answer

+5 votes

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

<?php
//C:\Internal\training-internal\Template.pptx

$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: https://www.youtube.com/watch?v=FIoQb0inLEM

...and 2 replace functions in PHP:

str replace php

answered by user hues
...