在PHP中没有Regex删除多个空格

时间:2021-11-15 02:05:39

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?

但是,正则表达式往往很慢,因为它必须加载正则表达式引擎。有非正则表达式方法吗?

3 个解决方案

#1


6  

try

while(false !== strpos($string, '  ')) {
    $string = str_replace('  ', ' ', $string);
}

#2


4  

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.

手工制作的功能在非常长(300kb +)的琴弦上运行速度大约快15%。

(on my machine at least)

(至少在我的机器上)

#3


1  

Well you could use trim or str_replace methods provided by php.

那么你可以使用php提供的trim或str_replace方法。

#1


6  

try

while(false !== strpos($string, '  ')) {
    $string = str_replace('  ', ' ', $string);
}

#2


4  

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.

手工制作的功能在非常长(300kb +)的琴弦上运行速度大约快15%。

(on my machine at least)

(至少在我的机器上)

#3


1  

Well you could use trim or str_replace methods provided by php.

那么你可以使用php提供的trim或str_replace方法。