Regex related tags like @Joe but not email addresses

In PHP, I want to get all tags (like @Joe) in a string, but not remove the email address (like ).

So in:

@Joe hello! @Dave email address is


I only want to combine @Joe and @Dave.

I am trying to create a regex

preg_match_all("([ ^]@[a-zA-Z0-9]+)", $comment, $atMatches); 


But this only matches @Dave (after removing the leading space).


source to share

4 answers

You can use \B

(rather than a string of words) an escape sequence to exclude matches that contain a word (for example, "dave" in the example text). Something like:

preg_match_all("/\B(@[a-zA-Z0-9]+)/", $comment, $atMatches); 


By the way, you are not using the correct delimiters in your syntax.



The following regex must match @Joe

and @Dave

, ignoring 's

both email addresses:


// ^@[a-zA-Z0-9]{1,}      matches @Name at the beginning of the line
// \s@[a-zA-Z0-9]{1,}     matches @Names that are preceded by a space (i.e. not an email address)




Well it sounds a lot like Twitter regex ...

You can try editing the following example from here .

function linkify_tweet($tweet) {
    $tweet = preg_replace('/(^|\s)@(\w+)/',
        '\1@<a href="\2">\2</a>',
    return preg_replace('/(^|\s)#(\w+)/',
        '\1#<a href="\2">\2</a>',




This one will match your example by ignoring emails and ""

preg_match_all("/(^|\s)(@.*?)['\s]/", $string, $matches);




All Articles