1

I need to normalize the spaces in a string:

  1. Remove multiple adjacent spaces
  2. Remove spaces at the beginning and end of the string

E.g. " my name is " => my name is

I tried

str_replace('  ',' ',$str);

I also tried php Replacing multiple spaces with a single space but that didn't work either.

Community
  • 1
  • 1
Rahul R
  • 209
  • 2
  • 11
  • 5
    The RegExp solution you linked seems like a fine solution. Why do you think it's not helpful to you? – Halcyon Feb 25 '13 at 16:19
  • 5
    ***How*** is that referenced question ***not*** helpful for your needs? – Kermit Feb 25 '13 at 16:19
  • i also want to remove space before and after string.. referenced code remove duplicate spaces and its different from my question – Rahul R Feb 25 '13 at 16:20
  • didn't you tried any one? preg_replace("/[[:blank:]]+/"," ",$input) –  Feb 25 '13 at 16:21
  • possible duplicate of [php Replacing multiple spaces with a single space](http://stackoverflow.com/questions/2368539/php-replacing-multiple-spaces-with-a-single-space) – Waleed Khan Feb 25 '13 at 16:23

3 Answers3

14

Replace any occurrence of 2 or more spaces with a single space, and trim:

$str = preg_replace('/ {2,}/', ' ', trim($input));

Note: using the whitespace character class \s here is a fairly bad idea since it will match linebreaks and other whitespace that you might not expect.

Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • Don't forget OP needs to trim spaces at the beginning and end of line. Updated the answer :) Also, if the real task is to replace all "whitespace" symbols: space, tab, vertical tab (anybody seen that ever?), etc. use `\s` instead of just ` ` – J0HN Feb 25 '13 at 16:25
0

Use a regex

$text = preg_replace("~\\s{2,}~", " ", $text);
Philipp
  • 15,377
  • 4
  • 35
  • 52
0

The \s approach strips away newlines too, and / {2,}/ approach ignores tabs and spaces at beginning of line right after a newline.

If you want to save newlines and get a more accurate result, I'd suggest this impressive answer to similar question, and this improvement of the previous answer. According to their note, the answer to your question is:

$norm_str = preg_replace('/[^\S\r\n]+/', ' ', trim($str));

In short, this is taking advantage of double negation. Read the links to get an in-depth explanation of the trick.

Community
  • 1
  • 1
Niki Romagnoli
  • 1,406
  • 1
  • 21
  • 26