How to remove all data after last dot using php?
Asked Answered
M

2

7

How to remove all data after last dot using php ?

I test my code. It's echo just aaa

I want to show aaa.bbb.ccc

How can i do that ?

<?PHP
$test = "aaa.bbb.ccc.gif";
$test = substr($test, 0, strpos($test, "."));
echo $test;
?>
Madelene answered 8/2, 2016 at 9:20 Comment(1)
You need strrpos instead of strpos.Americanism
W
9

You can try this also -

$test = "aaa.bbb.ccc.gif";

$temp = explode('.', $test);

unset($temp[count($temp) - 1]);

echo implode('.', $temp);

O/P

aaa.bbb.ccc

strpos — Find the position of the first occurrence of a substring in a string

You need to use strrpos

strrpos — Find the position of the last occurrence of a substring in a string

$test = "aaa.bbb.ccc.gif";
$test = substr($test, 0, strrpos($test, "."));
echo $test;

O/P

aaa.bbb.ccc
Wiggle answered 8/2, 2016 at 9:22 Comment(0)
E
13

You can utilize the function of pathinfo() to get everything before the dot

$str = "aaa.bbb.ccc.gif";
echo pathinfo($str, PATHINFO_FILENAME); // aaa.bbb.ccc
Experientialism answered 8/2, 2016 at 9:25 Comment(5)
pathinfo would be best for files.Wiggle
@Andrew, interesting solution!)Octane
@Sougata true, the reason I propose this solution is that I saw the string end with .gif and to me every string accepted function is just a way to manipulate a string :DExperientialism
if the string is a url it will strip everything but the filenameExpediency
This didn't quite format correctly for files with characters such as or Helm
W
9

You can try this also -

$test = "aaa.bbb.ccc.gif";

$temp = explode('.', $test);

unset($temp[count($temp) - 1]);

echo implode('.', $temp);

O/P

aaa.bbb.ccc

strpos — Find the position of the first occurrence of a substring in a string

You need to use strrpos

strrpos — Find the position of the last occurrence of a substring in a string

$test = "aaa.bbb.ccc.gif";
$test = substr($test, 0, strrpos($test, "."));
echo $test;

O/P

aaa.bbb.ccc
Wiggle answered 8/2, 2016 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.