Ali
Ali

Reputation: 267317

PHP ltrim() and rtrim() functions

I need two functions that take a string and the number of characters to trim from the right and left side and return it. E.g.:

$str = "[test]";
$str = ltrim($str, 1); // Becomes 'test]'
$str = rtrim($str, 1); // Becomes 'test'

How can I do it?

Upvotes: 1

Views: 14654

Answers (3)

SilentGhost
SilentGhost

Reputation: 320049

substr:

substr("abcdef", 0, -1);     // 'abcde'
substr("abcdef", 1);         // 'bcdef'

But that's not how ltrim, rtrim functions usually work. They operate with substrings and not indexes.

And obviously

substr('abcdef', 1, -1)

does what you want in one go.

Upvotes: 6

cletus
cletus

Reputation: 625485

function my_rtrim($str, $count) {
  return substr($str, 0, -$count);
}

function my_ltrim($str, $count) {
  return substr($str, $count);
}

See substr().

Upvotes: 6

Ivan Krechetov
Ivan Krechetov

Reputation: 19220

I believe substr() can do the job. Both the $start and $length arguments can be negative.

Upvotes: 2

Related Questions