John
John

Reputation: 13729

PHP trim inappropriate stripping

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
?>

Upvotes: 0

Views: 57

Answers (4)

Mark Baker
Mark Baker

Reputation: 212412

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

Upvotes: 4

Googlian
Googlian

Reputation: 6723

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

$file = 'vegas.css';
echo str_replace(".css", "", $file);

Upvotes: 1

MorganFreeFarm
MorganFreeFarm

Reputation: 3733

You can use basename() function:

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

// Return

vegas

Upvotes: 2

Susmita Mitra
Susmita Mitra

Reputation: 91

You can also try the following:

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

Upvotes: 0

Related Questions