Search code examples
phpstringextractexplode

Extracting string from file address


I have string like "/files/temp/ABCDxyz-dfgdf.jpg"

I need to extract ABCD. First I'm trying to get the whole filename with this

$file="/files/temp/ABCDxyz-dfgdf.jpg";
$fileName=explode("files/temp/",$file)[0];

But it is not working.


Solution

  • Use basename to get the filename without the directory:

    $filename = basename($file); // => ABCDxyz-dfgdf.jpg
    $beginning = substr($filename, 0, 4); // => ABCD