PHP has very rich collection of functions for strings manipulation. For trimming there are three functions:
1. trim()
Strip whitespace (or other characters) from the beginning and end of a string.
Parameters
str
-
The string that will be trimmed.
character_mask
-
Optionally, the stripped characters can also be specified using the
character_mask
parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
Examples
Example #1 Remove whitespaces
$text = "\t\tHello World ... ";
$trimmed = trim($text);
var_dump($trimmed);
Output:
string(28) "Hello World ..."
Example #2 Trim specific characters
$text = "Hello World";
$trimmed = trim($text, 'Hd');
var_dump($trimmed);
Output:
string(9) "ello Worl"
2. ltrim()
ltrim — Strip whitespace (or other characters) from the beginning of a string
Parameters
str
-
The input string.
- character_mask
-
You can also specify the characters you want to strip, by means of the
character_mask
parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
Examples
#Example 3
$text = "\t\tHello World ... ";
$trimmed = ltrim($text);
var_dump($trimmed);
Output:
string(16) "Hello World ... "
3. rtrim()
Strip whitespace (or other characters) from the end of a string
Parameters
str
-
The input string.
character_mask
-
You can also specify the characters you want to strip, by means of the
character_mask
parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
Examples
#Example 4
$text = "\t\tHello World ... ";
$trimmed = ltrim($text);
var_dump($trimmed);
Output:
string(16) "Hello World ... "
References
- http://php.net/manual/en/function.trim.php
- http://php.net/manual/en/function.ltrim.php
- http://php.net/manual/en/function.rtrim.php
Notes
Tutorial also referenced on stackoverflow.