简体   繁体   English

使用正则表达式将用户名替换为链接

[英]Using Regex to replace username with links

I'm using the Twitter API to fetch information about all of my followers. 我正在使用Twitter API来获取有关所有关注者的信息。 In many cases, their bio will have a link to their Instagram page. 在许多情况下,他们的履历将具有指向其Instagram页面的链接。 They usually define it by writing something along the lines of IG: myigusername94 or instagram - myigusername93 . 他们通常通过沿着IG: myigusername94编写一些东西来定义它IG: myigusername94instagram - myigusername93 I'm not that good with regex and I'd like to know how to test for the presence of a set of chars like ig: or 'instagram -` and replace it with 我对正则表达式不太满意,我想知道如何测试一组字符(如ig:或'instagram-')的存在并将其替换为

"ig: <a href="http://instagram.com/myigusername94">myigusername94</a>"

I know this is probably a simple fix. 我知道这可能是一个简单的解决方法。 But, I'm very new to regex. 但是,我对正则表达式非常陌生。

You can search using this regex: 您可以使用此正则表达式进行搜索:

\b(instagram|ig)\s*[:-]\s*\K([\w.]+)\b

And replace it by: 并替换为:

<a href="$1">$1</a>

RegEx Demo 正则演示

Code: 码:

$re = '/\b(instagram|ig)\s*[:-]\s*\K([\w.]+)\b/'; 

$result = preg_replace($re, '<a href="$1">$1</a>', $input);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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