Skip to content
Advertisement

replace multiple spaces in a string with a single space

I have a file with has several spaces among the words at some point. I need to clean the file and replace existing multi-spaced sequences with one space only. I have written the following statement which does not work at all, and it seems I’m making a big mistake.

 $s = preg_replace("/( *)/", " ", $x);

My file is very simple. Here is a part of it:

Hjhajhashsh dwddd dddd sss   ddd wdd ddcdsefe xsddd   scdc yyy5ty    ewewdwdewde           wwwe ddr3r dce eggrg               vgrg fbjb   nnn  bh jfvddffv mnmb   weer ffer3ef f4r4 34t4 rt4t4t 4t4t4t4t    ffrr  rrr  ww w w ee3e iioi   hj   hmm  mmmmm mmjm lk ;’’ kjmm  ,,,, jjj hhh  lmmmlm m mmmm lklmm jlmm m

Advertisement

Answer

Your regex replaces any number of spaces (including zero) with a space. You should only replace two or more (after all, replacing a single space with itself is pointless):

$s = preg_replace("/ {2,}/", " ", $x);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement