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.
Definition and Usage The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.
Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.
The trim() function in PHP removes whitespace or any other predefined character from both the left and right sides of a string. ltrim() and rtrim() are used to remove these whitespaces or other characters from the left and right sides of the string.
The ltrim() function removes whitespace or other predefined characters from the left side of a string. Related functions: rtrim() - Removes whitespace or other predefined characters from the right side of a string. trim() - Removes whitespace or other predefined characters from both sides of a string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With