How can regex be used to remove whitespaces between variable and fixed text in PHP?

When dealing with strings that have whitespaces between variable and fixed text in PHP, we can use regular expressions (regex) to remove these whitespaces. By using the preg_replace function with a regex pattern that matches whitespaces between the variable and fixed text, we can easily replace them with an empty string.

// Example string with whitespaces between variable and fixed text
$string = "Hello , World!";

// Using regex to remove whitespaces between variable and fixed text
$fixedText = "Hello";
$pattern = '/(' . preg_quote($fixedText, '/') . ')\s*,\s*(' . preg_quote("World!", '/') . ')/';
$replacement = '$1, $2';
$result = preg_replace($pattern, $replacement, $string);

// Output the result
echo $result; // Output: Hello, World!