/**
* Normalizes a string by trimming leading and trailing whitespace
* and collapsing multiple consecutive spaces into a single space.
*
* @param string $input
* @return string
*/
function removeExtraWhitespace(string $input): string
{
// Step 1: Use regular expression \s+ to match one or more contiguous whitespace characters
// (spaces, tabs, newlines) and replace each group with a single space.
$collapsed = preg_replace('/\s+/', ' ', $input);
// Step 2: Strip any leading or trailing whitespace left at the boundaries of the string.
return trim($collapsed);
}
// Input string containing variable padding and extra internal spaces
$s = " This is a test string with extra spaces. ";
// Clean and normalize the string
$cleanedString = removeExtraWhitespace($s);
echo $cleanedString . PHP_EOL;
/*
run:
This is a test string with extra spaces.
*/