views:

816

answers:

3

I need 2 functions that take a string and the number of chars 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

Thoughts?

+3  A: 
function my_rtrim($str, $count) {
  return substr($str, 0, -$count);
}

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

See substr().

cletus
Won't that give you an error for attempting to redefine the existing rtrim and ltrim functions?
ceejayoz
Rats, the names ltrim() and rtrim() are already in use by PHP. Any other names in mind for this, other than rSubstr() and lSubstr()?
Click Upvote
Yes it will and that's a good point even if slightly pedantic. :)
cletus
Lol. Any other creative names in mind other than rSubstr() and lSubstr()?
Click Upvote
trimL() and trimR() are two others...
Click Upvote
+2  A: 

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.

SilentGhost
+1  A: 

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

Ivan Krechetov