Search code examples
phpdetection

PHP Autolinking Usernames


I want to create a Autolinking solution for my Site. It's just about the Usernames, if a username is found in the string, it should create a link to the profile. Well, I had now just two possible solutions in mind:

  1. While extracting the usernames to give them an invisble special char as a kind of identifier and regex trough it. But this is just kind of a "luck" based solution and it won't go right in user-written texts.

  2. Getting a whole frking username array and pulling trough it everytime... I could reduce the serverload by reducing the detection to a limited factor as... let's say just the friends of the autor. But somehow this would be unstatisfying as well.

I would be glad for any kind of hint you may have. Usable are PHP, JS (JQuery FW).


Solution

  • To mimick Twitter and StackOverflow (using @), you could use something like this (demo):

    preg_replace('~(^|\s)@([[:alnum:]_]+)~', '$1<a href="/profile/$2/">@$2</a>', $string);