PHP's trim() is often underused. Usually web developers throw it in simply to prevent leading and trailing white spaces, but that's about it. What a lot of people seem to overlook is the fact that there is an optional second parameter which can make things a whole lot more useful.
A simple use of trim() would be something like this$s = " There are some white spaces around me ";
echo trim($s);
You can expect that this will result in "There are some white spaces around me." Pretty simple. Now, let's assume that you are looping through an array of strings and have produced a single comma separated string.$arr = Array('green', 'purple', 'gold', 'orange');
$s = '';
foreach($arr as $a) {
$s .= ', ' . $a;
}
echo $s;
This will output ", green, purple, gold, orange." But we don't want that leading comma and space. If you applied trim() like we did above it wouldn't change the string at all. But by passing a second parameter which defines what characters you will be trimming you can get the results you are looking for.$arr = Array('green', 'purple', 'gold', 'orange');
$s = '';
foreach($arr as $a) {
$s .= ', ' . $a;
}
echo trim($s, ', ');
This will output exactly what we want, "green, purple, gold, orange." It is important to understand that the second parameter ', ' is stating that any occurrence of either character at the beginning or end of the string will be trimmed, as you can see in the following.$s = "Hello World!";
echo trim($s, "dH!");
Since this trims any occurrence of either 'd,' 'H,' or '!' we end up with "ello Worl."
-
Utilizing PHP's Trim
1 Comment Posted on September 16th, 2009
1 Comment
Leave a Comment
-
You
Sep 7, 2010
$arr = array('green', 'purple', 'gold', 'orange');
$s = implode(', ', $arr);
echo $s;