Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP rtrim ".php"

Tags:

php

I want to remove ".php" from the end of a string if it exists. Consider this:

$filename = 'index';
rtrim($filename,".php");//returns "index"

$filename = 'search';
rtrim($filename,".php");//returns "searc"

Why is this happening? I feel like it has something to do with ending with the letter 'h' - 'h' being in the string in rtrim. So I tried a regular expression (.php$) to see if it made a difference but it didn't.

like image 858
Joao Avatar asked Dec 16 '22 05:12

Joao


1 Answers

rtrim accepts a list of characters as the second argument, so in this case, it will trim not just the .php extension, but any ., p, or h characters found in the rest of the string.

Try using preg_replace("/(.+)\.php$/", "$1", $filename); instead, or basename($filename, '.php') if you have the file on the server, not just in a string.

like image 125
jvperrin Avatar answered Dec 30 '22 20:12

jvperrin