How do you trim whitespace from the beginning and end of a string in PHP With Example?

Hello Friends Today, through this tutorial, I will tell you How do you trim whitespace from the beginning and end of a string using PHP, PHP 8, PHP 8.1, PHP 8.2, PHP 8.3 With Example. In PHP, you can trim whitespace (including spaces, tabs, and newlines) from the beginning and end of a string using the `trim()` function. Here’s how you can use it:

<?php

// Original string with leading and trailing whitespace
$string = " Hello, World! ";

// Trim whitespace from the beginning and end of the string
$trimmed_string = trim($string);

// Output the trimmed string
echo "Original string: '$string'<br>";
echo "Trimmed string: '$trimmed_string'";

?>

In this example, the `trim()` function removes any whitespace characters from the beginning and end of the original string. The trimmed string is then stored in the variable `$trimmed_string`.

After trimming, the output will be:

Original string: ' Hello, World! '
Trimmed string: 'Hello, World!'

This function is particularly useful when you need to sanitize user input or clean up strings obtained from external sources where leading and trailing whitespace might be present.