0

How do I stop PHP from outputting "vega" when it should be outputting "vegas" using the following code?

<?php
$file = 'vegas.css';
echo rtrim($file,'.css');
//Wrong/current echo/output: vega
//Desired echo: vegas
?>
John
  • 1
  • 13
  • 98
  • 177
  • 1
    `echo implode('', explode('.css', $file));` ? – funilrys Feb 02 '19 at 19:33
  • 2
    or `echo explode('.css', $file)[0];` – funilrys Feb 02 '19 at 19:34
  • 1
    https://stackoverflow.com/questions/46307527/why-is-rtrim-removing-more-characters-and-giving-weird-output/46307606 – The fourth bird Feb 02 '19 at 19:34
  • Possible duplicate of [PHP, get file name without file extension](https://stackoverflow.com/questions/2183486/php-get-file-name-without-file-extension) – Mike Doe Feb 02 '19 at 19:34
  • @funilrys Either or and Mark's answer combined would be the most appropriate way to *answer* the question. – John Feb 02 '19 at 19:35
  • Possible duplicate of [Why is rtrim removing more characters, and giving weird output?](https://stackoverflow.com/questions/46307527/why-is-rtrim-removing-more-characters-and-giving-weird-output) – Jaquarh Feb 02 '19 at 19:37

4 Answers4

4

Understand that the second argument to trim functions like rtrim is a set of characters, so you're trying to strip every instance of the characters s, c and . from the end of your string, not an ordered sequence of characters. That's why it also removes the trailing s from vegas as well.

From the php.net documentation:

character_mask

You can also specify the characters you want to strip, by means of the character_mask parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Better test that the end of your string is .css and then substring the last 4 characters

Community
  • 1
  • 1
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • ...and no explicit mention of this on php.net could have been made in the official documentation? -_- Thank you. – John Feb 02 '19 at 19:37
3

You can use basename() function:

<?php
$file = 'vegas.css';
$file = basename($file, ".css");
echo $file;

// Return

vegas
MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46
1

You can use str_replace to replace the text with empty value:

$file = 'vegas.css';
echo str_replace(".css", "", $file);
Googlian
  • 6,077
  • 3
  • 38
  • 44
0

You can also try the following:

echo basename('file.csv','.csv');

Susmita Mitra
  • 91
  • 1
  • 2