I need to remove excess whitespaces from my players usernames in my application (more than once space between开发者_StackOverflow社区 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!
preg_replace('/\s+/', ' ', $string);
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);
try preg_replace like this:
preg_replace('/\s{2,}/', ' ', $str);
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?
精彩评论