22

How to trim multiple characters at begin and end of string.
string should be something like {Hello {W}orld}.
i want to trim both { and } at begin and end.

don't want to use multiple trim function.

hakre
  • 193,403
  • 52
  • 435
  • 836
امین کرمی
  • 257
  • 1
  • 2
  • 6
  • 3
    You can provide an optional charlist to the `trim` function, as the [manual explains](http://php.net/manual/en/function.trim.php). *Simply list all characters that you want to be stripped. With .. you can specify a range of characters.* – Rem.co Jun 27 '12 at 12:47
  • thank you, just don't know why people are voting down – امین کرمی Jun 27 '12 at 13:12
  • I assume that all initial downvotes were because you were asking a very simple question which could have been avoided if you simply cracked open the freely available online php manual. – mickmackusa Mar 12 '22 at 12:24

2 Answers2

37

Use the optional second argument to trim which allows you to specify the list of characters to trim:

<?php
$str = "{Hello {W}orld}";
$str = trim($str, "{}");

echo "Trimmed: $str";

Output:

Trimmed: Hello {W}orld
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
-3

Is there always a character at the beginning and at the end, that you want to remove? If so you could just use the following:

<?php
$string = '{Hello {W}orld}';
echo substr( $string, 1, strlen( $string )-2 );
?>

See: http://codepad.org/IDbG6Km2

Louis B.
  • 2,348
  • 1
  • 29
  • 51