How can the trim function in PHP be used to remove unnecessary characters at the beginning and end of a text string, and what are its limitations?

The trim function in PHP can be used to remove unnecessary characters such as whitespace, tabs, or newlines at the beginning and end of a text string. This is useful for cleaning up user input or data retrieved from a database. The trim function does not remove characters in the middle of the string, only at the beginning and end.

$string = "   Hello World!   ";
$trimmed_string = trim($string);
echo $trimmed_string; // Output: "Hello World!"