2011-06-30 27 views
1

我需要找到冒号“:”的第一个出现位置,然后取出完整的字符串并将其附加到链接。PHP正则表达式将冒号前的文本转换为链接

例如

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到一个可点击的网址:

例如

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

任何想法:)

+0

名称总是在字符串的开头吗? –

+0

总是在开始。 – CLiown

+0

'username:'和'@ twitter'应该是2个不同的链接吗?因为转换后'@ twitter'在你的例子中消失了。 – Karolis

回答

0

我没有测试的代码,但它应该工作原样。基本上你也需要在@twitter之后捕获。

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

我会使用字符串操作对于这一点,而不是正则表达式,使用strstrsubstrstrlen

$username = strstr($description, ':', true); 
$description = '<a href="http://twitter.com/' . $username . '">' . $username . '</a>' 
      . substr($description, strlen($username)); 
0

下应该努力 -

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

直接回答你的问题:

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

但我认为你解析twitter RSS或类似的东西。所以你可以使用/^(\w+)/

相关问题