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,538
  • 3
  • 14
  • 24
  • 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
  • 348,685
  • 41
  • 398
  • 480
  • 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
  • 45,211
  • 10
  • 74
  • 119
0

try preg_replace like this:

preg_replace('/\s{2,}/', ' ', $str);
anubhava
  • 713,503
  • 59
  • 514
  • 593
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,672
  • 11
  • 72
  • 123