Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple white spaces without Regex in PHP

Tags:

regex

php

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?

like image 633
Leo Jiang Avatar asked Dec 22 '22 01:12

Leo Jiang


2 Answers

try

while(false !== strpos($string, '  ')) {
    $string = str_replace('  ', ' ', $string);
}
like image 68
silly Avatar answered Dec 24 '22 01:12

silly


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)

like image 21
Yoshi Avatar answered Dec 24 '22 00:12

Yoshi