PHP正则表达式将冒号前的文本转换为链接 [英] PHP Regex to convert text before colon to link
本文介绍了PHP正则表达式将冒号前的文本转换为链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到第一次出现的冒号 ':' 并在此之前获取完整的字符串并将其附加到链接中.
I need to find the first occurance of a colon ':' and take the complete string before that and append it to a link.
例如
username: @twitter nice site! RT www.google.com : visited!
需要转换为:
<a href="http://twitter.com/username">username</a>: nice site! RT www.google.com : visited!
我已经有了以下将字符串@twitter 转换为可点击 URL 的正则表达式:
I've already got the following regex that converts the string @twitter to a clickable URL:
例如
$description = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $description);
任何想法:)
推荐答案
为此我会使用字符串操作,而不是正则表达式,使用 strstr
, substr
和 strlen
:
I'd use string manipulation for this, rather than regex, using strstr
, substr
and strlen
:
$username = strstr($description, ':', true);
$description = '<a href="http://twitter.com/' . $username . '">' . $username . '</a>'
. substr($description, strlen($username));
这篇关于PHP正则表达式将冒号前的文本转换为链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文