0

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!

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87

3 Answers3

0

Try the following:

echo substr('Hello.World.pdf', 0, strrpos('Hello.World.pdf', '.'));

Reading material:

http://php.net/manual/en/function.strrpos.php

http://php.net/manual/en/function.substr.php

Note: I recommend you verify that strrpos actualy returns a valid value.

EDIT:

$haystack = 'Hello.World.pdf';
$needle = '.';
$pos = strrpos($haystack, $needle);

echo ($pos === false ? $haystack : substr($haystack, 0, $pos));
0

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

junkystu
  • 1,427
  • 1
  • 13
  • 15
0

Since you're interested in filenames and extensions; junkstu almost had it, but you can just use PATHINFO_FILENAME to get the filename without the extension:

echo pathinfo("Hello.World.pdf", PATHINFO_FILENAME);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87