php - preg_replace with similar values -


i working on mentions system , have run across problem, when looping through , changing mentions links, replace similar ones such @tom , @tom123 same link /tom/ instead of individual.

i have tried using regex , preg_replace checking see if username exists, wondering if there way can prevent happening.

$tweet = "@wayne how you? @wayne123 cool you?";          preg_match_all('/(^|\s)@([a-z0-9_]+)/i', $tweet, $matches);         $i = 0;          foreach( $matches[2] $value )          {                 if ( $db_query )             {                 $tweet = str_replace("@" . $value, "<a href=\"/user/$value\">@$value</a>!", $tweet);             }                        }          echo $tweet; // outputs: hi <a href="/user/wayne">@wayne!</a> how you? <a href="/user/wayne">@wayne!</a>123 cool you? 

any appreciated, have tried regex before continues along line , updates others before able check see if valid user

the problem first time through loop @wayne123 replaced @wayne can't find match second time through loop.

use preg_replace references.

$tweet = "@wayne how you? @wayne123 cool you?"; $pattern = '/(^|\s)@(\w+)/'; $replacement = '<a href="/user/$2">@$2</a>'; print preg_replace($pattern, $replacement, $tweet); 

in $replacement $2 replaced match of second set of parenthesis (\w)

note (\w) shorthand ([a-za-z0-9_])


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -