开发者

PHP Regex to convert text before colon to link

I need to find the first occurance of a colon ':' and take the complete string before that and append it to a link.

e.g.

username: @twitter nice sit开发者_C百科e! RT www.google.com : visited!

needs to be converted to:

<a href="http://twitter.com/username">username</a>: nice site! RT www.google.com : visited!

I've already got the following regex that converts the string @twitter to a clickable URL:

E.g.

$description = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $description);

Any ideas : )


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));


$regEx = "/^([^:\s]*)(.*?:)/";
$replacement = "<a href=\"http://www.twitter.com/\1\" target=\"_blank\">\1</a>\2";


I have not tested the code, but it should work as is. Basically you need to capture after @twitter too.

$description = preg_replace("%([^:]+): @twitter (.+)%i", 
    "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>: \\2", 
    $description);


The following should work -

$description = preg_replace("/^(.+?):\s@twitter\s(.+?)$/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>: \\2", $description);


Direct answer to your question:

$string = preg_replace('/^(.*?):/', '<a href="http://twitter.com/$1">$1</a>:', $string);

But I assume that you are parsing twitter RSS or something similar. So you can just use /^(\w+)/.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜