phpstrrchr

What is opposite of strrchr function?


I want to remove all characters after last specific string. For this function I need opposite of strrchr function.

For example, I want to remove all characters after last "." from "Hello.World.pdf". But with strrchr function I can only remove "Hello.World" before "."!

I want something like this code:

<?php
echo strrchr("Hello.World.pdf" , "." , true);
?>

But this code isn't working!


Solution

  • If you are dealing with file names that can have various extensions and you would like to remove the extension, you can get the extension using pathinfo() and then use str_replace() to get rid of it:

    $filename  = 'Hello.World.pdf';
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    $filename  = str_replace('.' . $extension, '', $filename);
    echo $filename; //Hello.World
    

    More info on pathinfo and str_replace