0

I need to remove excess whitespaces from my players usernames in my application (more than once space between letters) and replace them with a single whitespace. I do not mind users having a single whitespace, but I need to remove multiple whitespaces next to each other. Currently I achieve it this way:

$replace_array=array('  ','   ','    ','     ','      ','       ','        ','             ','          ','           ','            ','             ','              ','               ');
$fill_array=array('','','','','','','','','','','','','','');

$user_name=str_replace($replace_array,$fill_array,trim($_POST['name']));
$user_name=preg_replace('/[^a-zA-Z0-9 ]/','',$user_name);

That seems entirely unnecessary to remove excess whitespaces. Does, perhaps, the preg_replace function already handle excess whitespaces? If not, what should I do to simplify this part of my code.

Thanks!

Phillip
  • 1,558
  • 3
  • 15
  • 25
  • possible duplicate of [remove multiple whitespaces in php](http://stackoverflow.com/questions/2326125/remove-multiple-whitespaces-in-php) – John Flatness Aug 16 '11 at 17:26

4 Answers4

6
preg_replace('/\s+/', ' ', $string);
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • How would I combine my current preg_replace function with this one? I need to study this function a bit more. – Phillip Aug 16 '11 at 17:25
  • `$user_name = preg_replace('/\s+/', ' ', $user_name);`, then do the second preg_replace as usual. mixing regexes that have different purposes will usually only end up biting you in the butt, so keep them separate. – Marc B Aug 16 '11 at 17:27
  • @Phillip better use you regexp first then this regexp. or "aaa & aaa" will fail – RiaD Aug 16 '11 at 18:35
1

find 1 or more space and replace by 1 space:

preg_replace('/\s+/',' ',$user_name)

Also you can use 1 preg-replace statement

$user_name=preg_replace('/([^a-zA-Z0-9 ]|\s+)/','',$user_name);
RiaD
  • 46,822
  • 11
  • 79
  • 123
0

try preg_replace like this:

preg_replace('/\s{2,}/', ' ', $str);
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

my understanding is that simply using str_replace(' ', '') will fix your issue. It replaces multiple occurances of a space. Also have you tried using ltrim?

Toby Allen
  • 10,997
  • 11
  • 73
  • 124