Web Development & WordPress

PHP String Trimming Functions

Here you can see how to remove unnecessary whitespace and specific characters from the beginning and end of strings using PHP’s trim(), ltrim(), and rtrim() functions.

Code:

<?php
$stringTrim = "  , Hello World  \t ,  ";
$anothrerWord ="Great";

echo $stringTrim;
echo $anothrerWord;

echo '<br>After using Trimming function trim($stringTrim) :<br>';
echo trim($stringTrim);
echo $anothrerWord;

echo '<br>After using Trimming function trim($stringTrim, \'  ,\') :<br>';
echo trim($stringTrim, ' ,');
echo $anothrerWord;

echo '<br>After using Trimming function ltrim($stringTrim, \'  ,\') :<br>';
echo ltrim($stringTrim, ' ,');
echo $anothrerWord;

echo '<br>After using Trimming function rtrim($stringTrim, \'  ,\') :<br>';
echo rtrim($stringTrim, ' ,');
echo $anothrerWord;
?>

Output

, Hello World , Great
After using Trimming function trim($stringTrim) :
, Hello World ,Great
After using Trimming function trim($stringTrim, ' ,') :
Hello World Great
After using Trimming function ltrim($stringTrim, ' ,') :
Hello World , Great
After using Trimming function rtrim($stringTrim, ' ,') :
, Hello World Great

Leave a comment