简体   繁体   中英

Regex to match and replace string

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

$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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM