What are some best practices for handling string manipulation in PHP to avoid duplicate output?

When handling string manipulation in PHP, one common issue is accidentally outputting duplicate strings due to improper concatenation or manipulation. To avoid this, it's best to use PHP functions like trim(), rtrim(), ltrim(), or preg_replace() to remove any unwanted characters or spaces before concatenating or manipulating strings.

// Example code snippet to avoid duplicate output when manipulating strings in PHP
$string1 = "Hello, ";
$string2 = "World!";

// Remove any unwanted characters or spaces before concatenating strings
$string1 = rtrim($string1, ',') . " "; // Remove any trailing commas
$string2 = ltrim($string2); // Remove any leading spaces

echo $string1 . $string2; // Output: Hello, World!