Introduction
I am showing the use of the "trim", "ltrim" and "rtrim" string functions in PHP. These functions are primarily used to remove spaces in a string. The trim function removes spaces from both sides of the string, The ltrim function removes spaces from the left of the string and rtrim function removes spaces from the right of the string. Here I show step-by-step the use of the string trimming functions. First I show the use of the trim function in PHP.
String trim Function
The trim function removes spaces from both sides of the string.
Syntax
Example
<html>
<body>
<?php
$tr = " Hello MCN! ";
echo "Without trim: " . $tr;
echo "<br />";
echo "With trim: " . trim($tr);
?>
</body>
</html>
Output
You will see the difference in the source code and the output of the trim() function. To view the source code, right-click on the output and then you will see the source.
String ltrim Function
The ltrim function removes spaces from the left side of the string.
Syntax
Example
<html>
<body>
<?php
$tr = " This is Ltrim function!";
echo "Without ltrim: " . $tr;
echo "<br />";
echo "With ltrim: " . ltrim($tr);
?>
</body>
</html>
Output
You will see the difference in the source code and the output of the ltrim() function. To view the source code, right-click on the output and then you will see the source.
String rtrim Function
The rtrim function removes spaces from the right side of the string.
Syntax
Example
<html>
<body>
<?php
$tr = "This is Rtrim function! ";
echo "Without rtrim: " . $tr;
echo "<br />";
echo "With rtrim: " . rtrim($tr);
?>
</body>
</html>
Output
You will see the difference in the source code and the output of the rtrim() function. To view the source code, right-click on the output and then you will see the source.