Introduction
When working with text data in PHP, you'll frequently find yourself needing to remove unwanted spaces from the start or end of a string. Thankfully, PHP provides us with a handy built-in function, trim(), designed to do exactly that.
In this blog, we will learn about PHP trim() function.
What is the PHP trim() Function?
The trim() function in PHP is used to remove whitespace characters from the beginning and end of a string. Not only spaces, but it also removes other types of characters such as tabs (\t), newlines (\n), and carriage returns (\r).
Here is the basic syntax:
trim($string, $character_mask);
The $string parameter is required and represents the string to be trimmed. The $character_mask parameter is optional and allows you to specify which characters you want to remove from the string.
Using the trim() Function
Let's see a simple usage of trim() function:
$text = " Hello, World! ";
$trimmed = trim($text);
echo $trimmed; //
Outputs:
"Hello, World!"
In this example, the trim() function is used to remove the leading and trailing spaces from the string.