Reputation: 201
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
Upvotes: 2
Views: 154
Reputation: 6555
$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
Upvotes: 4
Reputation: 145512
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.
Upvotes: 2