PHP & MySQL | Tutorials

David Carr

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';
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.

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.