+2 votes
in Programming Languages by (7.0k points)

I want to delete whitespace and newline characters from the left and right sides of a string. What PHP function(s) should I use?



"\n hello world \n\n"


"hello world"

1 Answer

0 votes
by (28.9k points)

You can use the trim() function to remove whitespace or other predefined characters from both sides of a string.

If you want to remove from only the left side, you can use the ltrim() function.

If you want to remove from only the right side, you can use the rtrim() function.

If you do not specify which character needs to be removed, these functions will remove the following characters:

"\0" - NULL
"\t" - tab
"\n" - new line
"\x0B" - vertical tab
"\r" - carriage return
" " - white space

Here is an example:

$str = "\n hello world \n\n";
echo $str;
echo trim($str);

The above code will return the following output:

 hello world

hello world