RegEx to match / link Twitter usernames and hashtags

One of the things we do at Helpful Technology is provide digital skills training. As part of that we have a sandboxed Twitter style social network platform that allows users to get used to the medium and practice in a safe environment.

I’ve been re-building this system recently, and one feature we wanted to add was the automatic linking of usernames and hashtags. This is fairly simple to do with a bit of RegEx in PHP – and on WordPress you can just attach it to the filter called the_content to process all text before it is output and insert links as needed. The code could be put in a plugin, but here it’s written so you can just drop it in to your functions.php.

If you’re wondering about the ‘weird’ \p{X} statements – that’s using PHP’s unicode character properties to ensure all languages are matched.



Leave a Reply

Your email address will not be published. Required fields are marked *