Search for @mentions in a string

Trying to replace all @mention occurrences with an anchor tag while I have:

$comment = preg_replace('/@([^@ ])? /', '<a href="/$1">@$1</a> ', $comment);

Take the following sample line:

"@name kdfjd fkjd as@name @ lkjlkj @name"

So far so good, but I want to ignore this single "@" character. I tried using "+" and "{2,}" after "[^ @]", which I thought would provide a minimal number of matches, but it does not work.

+3
source share
6 answers

Replace the question mark quantum ( ?) ("optional") and add +("one or more") after your character class:

@([^@ ]+)
+8
source

Regular expression

(^|\s)(@\w+)

Perhaps you will be after.

, @, 1 .

.

preg_match_all('/(^|\s)(@\w+)/', '@name1 kdfjd fkjd as@name2 @ lkjlkj @name3', $result);
var_dump($result[2]);

Array
    (
        [0] => @name1
        [1] => @name3
    )
+5

,

preg_replace('/(^|\s)@([\w_\.]+)/', '$1<a href="/users/$2">@$2</a>', $text);

:

  • @ . URL
  • _ .
  • , $1 ,
+3

? + , , .

@name .

$comment = preg_replace('#@(\w+)#', '<a href="/$1">$0</a> ', $comment);

, . \w+ (a-zA-Z0-9)

+2

Try:

'/@(\w+)/i'

0

$comment = preg_replace('/@([^(@|\s)]+)/', '<a href="/$1">@$1</a>', $comment);

.

-6
source

All Articles