Remove some white spaces without regex in PHP

The general solution for turning multiple white spaces into one empty space is a regular expression:

preg_replace('/\s+/',' ',$str); 

However, the regex tends to be slow because it has to load the regex engine. Are there any non-regex methods?

+4
source share
3 answers

try

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

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 with:

 preg_replace('/(\s)\s+/', '$1', $str); 

The manual function works about 15% faster with very long (300 kb +) lines.

(at least in my car)

+4
source

Well, you can use the trim or str_replace methods provided by php.

+1
source

Source: https://habr.com/ru/post/1398239/


All Articles