The common solution to turn multiple white spaces into one white space is by using regular expression like this:
preg_replace('/\s+/',' ',$str);
However, regex tends to be slow because it has to load the regular expression engine. Are there non-regex methods to do this?
try
while(false !== strpos($string, ' ')) {
$string = str_replace(' ', ' ', $string);
}
Update
function replaceWhitespace($str) {
$result = $str;
foreach (array(
" ", " \t", " \r", " \n",
"\t\t", "\t ", "\t\r", "\t\n",
"\r\r", "\r ", "\r\t", "\r\n",
"\n\n", "\n ", "\n\t", "\n\r",
) as $replacement) {
$result = str_replace($replacement, $replacement[0], $result);
}
return $str !== $result ? replaceWhitespace($result) : $result;
}
compared to:
preg_replace('/(\s)\s+/', '$1', $str);
The handmade function runs roughly 15% faster on very long (300kb+) strings.
(on my machine at least)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With