Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php to replace @username with link to twitter account

Tags:

regex

php

I assume this is some to do with regex, but it's an art all it's own - and I need some help.

When we display a story, we store all the text in a varilable - let's say $story.

What i'd like is to do a str_replace (I think that's what I need) that says something like this "If the text contains @something then turn it into a link like <a href="http://www.twitter.com/something">@something</a>- but only do this if there's nothing before the @ symbol" (to exclude email addresses)

Also, we'd need to stop the 'something' if there's a space or punctuation after it. so that @something. doesn't turn into <a href="http://www.twitter.com/something.">@something.</a>

Any suggestions on how to make this work?

like image 234
Andelas Avatar asked Jan 22 '11 04:01

Andelas


2 Answers

$input = preg_replace('/(^|\s)@([a-z0-9_]+)/i',
                      '$1<a href="http://www.twitter.com/$2">@$2</a>',
                       $input);

See it

It matches a @ which is preceded by whitespace or nothing ( when it is at the beginning).

It can also be shorted using positive lookbehind as:

$input = preg_replace('/(?<=^|\s)@([a-z0-9_]+)/i',
                      '<a href="http://www.twitter.com/$1">@$1</a>',
                      $input);

Which matches only the twitter name but only if there is space or nothing before that.

like image 146
codaddict Avatar answered Oct 08 '22 01:10

codaddict


A positive lookbehind could do the trick:

preg_replace('/(?<=\s)@(.*?)/', '<a href="....com/$1">@$1</a>')

going off the top of my head. "If there's a @ which is preceded by something which is whitespace, then take whatever follows after the @ and do the html tag wrapping".

like image 20
Marc B Avatar answered Oct 08 '22 03:10

Marc B