[Solved] Extract File - String Task

  

3
Topic starter

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

Examples:

extract file string task

1 Answer
2

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: 

...and 2 replace functions in PHP:

str replace php

Share: