Trim String in PHP

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

trim(string,$var);

 

Example

 

<html>

<body>

<?php

$tr = "       Hello MCN!        ";

echo "Without trim: " . $tr;

echo "<br />";

echo "With trim: " . trim($tr);

?>

</body>

</html>

Output

trim2 in php.jpg

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.

trim in php.jpg

String ltrim Function

The ltrim function removes spaces from the left side of the string.

Syntax

ltrim(string,$var);

 

Example

 

<html>

<body>

<?php

$tr = "        This is Ltrim function!";

echo "Without ltrim: " . $tr;

echo "<br />";

echo "With ltrim: " . ltrim($tr);

?>

</body>

</html>

Output

ltrim2 in php.jpg

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.

ltrim in php.jpg

String rtrim Function

The rtrim function removes spaces from the right side of the string.

Syntax

rtrim(string,$var);

 

Example

<html>

<body>

<?php

$tr = "This is Rtrim function!        ";

echo "Without rtrim: " . $tr;

echo "<br />";

echo "With rtrim: " . rtrim($tr);

?>

</body>

</html>

Output

rtrim in php.jpg

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.

rtrim2 in php.jpg

 

Up Next
    Ebook Download
    View all
    Learn
    View all