EnderWiggins
EnderWiggins

Reputation: 390

removing "@something" with preg_replace()

In the stack-overflow question here , it was explained that you can remove emails with this code:

$pattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/";
$replacement = "[removed]";
preg_replace($pattern, $replacement, $string); 

This removes stuff like [email protected] - how do I modify the regular expression so that I remove something like @johnDoe from a chunk of text?

I really don't understand regular expression that well.

Upvotes: 0

Views: 99

Answers (1)

luiges90
luiges90

Reputation: 4598

use

$pattern = "/@[^@\s]*/";

In [^@\s]:

  • \s stands for any space character
  • [@\s] stands for a character group, containing \s (i.e. space) and the @ character. it matches either @ or \s
  • [^@\s] stands for the character group that is not @\s
  • afterall, [^@\s] matches a single character that is not @ character or \s (i.e. spaces)

* after it stands for the previous token (i.e. [^@\s] here) can repeat zero or more times. Hence, [^@\s]* matches string of any length as long as it does not contain @ or \s


As a side note, your link give a much-simplified regex for matching e-mails. The perfect way of matching e-mails are no simple matter.

Upvotes: 1

Related Questions