Tutorials, PHP & MySQL

Regular expression to convert usernames into links like Twitter

When using plain textareas it's useful to link usernames in the format as @name but won’t use email addresses. 

$subject = 'Hello, @daveismyname twitter handle is clickable but not this email someone@domain.com';
echo preg_replace('/\B\@([a-zA-Z0-9_]{1,254})/', '<a href="user/$1">$0</a>', $subject)

This looks for a non–word-boundary (to prevent a@b [i.e. emails] from matching) followed by @, then between one and 20 (inclusive) characters in that character class. Of course, the anything-except-space route, as in other answers; it depends very much on what values are to be (dis)allowed in the label part of the @label.

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.