Reputation: 267317
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
Reputation: 320049
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
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
Reputation: 19220
I believe substr() can do the job. Both the $start and $length arguments can be negative.
Upvotes: 2