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 dave@example.com ).

So in:

@Joe hello! @Dave email address is dave@example.com

      

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).

+3


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.

+6


source


The following regex must match @Joe

and @Dave

, ignoring 's

both email addresses:



(^@[a-zA-Z0-9]{1,})|(\s@[a-zA-Z0-9]{1,})

// ^@[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)

      

+1


source


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="http://www.twitter.com/\2">\2</a>',
        $tweet);
    return preg_replace('/(^|\s)#(\w+)/',
        '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>',
        $tweet);
}

      

0


source


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

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

      

0


source







All Articles