August 17, 2024
PHP removing extra spaces or characters using trim()
Some times it happens you want to remove spaces or any other character from the right and left side from a string. So you can easily do that with using trim function. trim function requires two arguments first is the string from where you want to remove spaces or character or second is character which you want to trim. Second parameter is optional if you do not pass second parameter then it assume you want to remove spaces and if you want to remove any other character then spaces then you will have to pass second parameter. trim function removes spaces or character from the left and right side of the string, but if you want to remove spaces or character only from one side so for the same you can use rtrim or ltrim function for removing character from right or left side respectively. The example of trim function is mentioned below:
Code
<?php
$msgVariable = " Hello ";
// below mentioned statement remove the spaces from the both side
$trimMessage = trim($msgVariable);
echo $trimMessage;
// below mentioned statement will remove o from Hello word
$newString = rtrim($trimMessage, "o");
// below statement will print "Hell" on the screen
echo $newString;
// below statement will remove H from the left
$newString2 = ltrim($newString, "H");
// below statement will print "ell" on the screen.
echo $newString2;
?>