0

I want to replace non-word non-space characters with spaces. There can be many symbol characters consecutively, so I'm using the regex below

[^\s\w]*

So, the code I'm using is:

$str = 'email@domain.com';
echo preg_replace('/[^\s\w]*/', ' ', $str); 

I was expecting to get email domain com but I get e m a i l d o m a i n c o m, whitespaces between each character. If I remove the asterisk like following

echo preg_replace('/[^\s\w]/', ' ', $str);

then I get the desired email domain com. But if input is email@@domain.com then this regex will give email domain com with two whitespaces between email and domain, which is not what I want.

Can anyone explain why [^\s\w]* doesn't work, and how can I achieve what I want?

NecipAllef
  • 427
  • 1
  • 3
  • 16

1 Answers1

1

This is happening because the asterisk matches 0 or more instances of [^\s\w]. So it's matching 0 instances, and then replacing it with a space. Use plus (+) if you want to make sure there's at least one match: /[^\s\w]+/.

sorayadragon
  • 1,012
  • 6
  • 20