How to trim whitespace from a string in PHP?

by cortez.connelly , in category: PHP General , 2 years ago

How to trim whitespace from a string in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , 2 years ago

@cortez.connelly 

In PHP, you can trim whitespace from a string using the trim() function. The trim() function removes whitespace from both the beginning and end of a string. Here's an example:

1
2
3
$str = "   Hello, World!   ";
$str = trim($str);
echo $str; // Output: "Hello, World!"


In the example above, the trim() function removes the whitespace from the beginning and end of the $str variable, resulting in the output of "Hello, World!" without the leading and trailing spaces.


If you want to remove only the whitespace from the beginning of the string, you can use the ltrim() function. Similarly, if you want to remove only the whitespace from the end of the string, you can use the rtrim() function. Here's an example:

1
2
3
4
5
6
7
$str = "   Hello, World!   ";
$str = ltrim($str);
echo $str; // Output: "Hello, World!   "

$str = "   Hello, World!   ";
$str = rtrim($str);
echo $str; // Output: "   Hello, World!"


In the example above, the ltrim() function removes the whitespace from the beginning of the string, and the rtrim() function removes the whitespace from the end of the string, resulting in different outputs.