Timm
Timm

Reputation: 12753

Regex match tags like @Joe but not email addresses

In PHP, I want to get all the tags (e.g. @Joe) in a string, but avoid email address (e.g. [email protected]).

So in:

@Joe hello! @Dave's email address is [email protected]

I want to only match @Joe and @Dave .

The regex I'm trying is

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

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

Upvotes: 3

Views: 223

Answers (4)

Michael
Michael

Reputation: 1227

This one will match your example, ignoring e-mails and " ' "

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

Upvotes: 0

Rijk
Rijk

Reputation: 11301

You could use the \B (not a word boundry) escape sequence to exclude the matches that have a word (like "dave" in the example text) before it. Something like:

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

By the way, you're not using proper delimiters in your syntax.

Upvotes: 6

augustknight
augustknight

Reputation: 448

The following regex should match @Joe and @Dave while ignoring the 's and 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)

Upvotes: 1

Paul Bain
Paul Bain

Reputation: 4397

Well that sounds very similar to a Twitter regex...

You could 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);
}

Upvotes: 0

Related Questions