echo correctSpacing_1(" my   name   is Slim Shady  ")."\n";
echo correctSpacing_2(" my   name   is Giovani Giorgio  ")."\n";

//Using explode function
function correctSpacing_1($sentence) {
	$array = explode(' ', $sentence);
	$count = count($array);
	for ($i = 0; $i < $count; $i++) {
		if (!$array[$i]) {
			unset ($array[$i]);
		}
	}
	return implode(' ', $array);
}

//Using while loop
function correctSpacing_2($sentence) {
	$sentence = trim($sentence);
	while (str_contains($sentence, '  ')) {
		$sentence = str_replace('  ', ' ', $sentence);
	}
	return $sentence;
}
by ვაჟა ტყემალაძე
2 years ago
PHP
Problem Solving
php
Note
Problem
0
Pro tip: use ```triple backticks around text``` to write in code fences