2

I want to match twitter usernames and replace it with a string. This is with PHP

This is the regex I have

/(^|[^a-z0-9_])[@@]([a-z0-9_]{1,20})([@@\xC0-\xD6\xD8-\xF6\xF8-\xFF]?)/iu

I have a string like

RT @omglol I am hungry @lolomg bla

I want to replace every username there with a html tag like

<a href="http://lol.com">@omglol</a>

How can I do this? Thaks for answers

3
  • can you post the code you have tried too? Commented Nov 19, 2011 at 10:01
  • why is there a slim and a fat @ in this question..? Commented Nov 19, 2011 at 10:09
  • @BillyMoon Some people tweet with @ and @ I want to match them all. Commented Nov 19, 2011 at 10:10

2 Answers 2

4
$s = "RT @omglol I am hungry @lolomg bla";
$p = "/(@\w+)/";
$r = '<a href="http://lol.com">$1</a>';
print preg_replace($p, $r, $s);

=> RT <a href="http://lol.com">@omglol</a> I am hungry <a href="http://lol.com">@lolomg</a> bla
Sign up to request clarification or add additional context in comments.

Comments

2

You would use preg_replace for that. Since you have the regex, you just need to construct a $replacement pattern. Use $1 and $2 and $3 placeholders in it, where each of them corresponds to a (...) capture group.

 $text = preg_replace(YOUR_REGEX, "$1<a href=$2>:)$2</a>$3", $text);

Your regex isn't very clever, but might work with that. Also you can add a base URL / prefix for the href= of course.

If you do need to transform the twitter name into a more complex URL somehow, then you'd probably want to use preg_replace_callback instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.