PHP正则表达式检测@twitter然后创建url

时间:2015-07-26 15:18:20

标签: php regex

我想检测@ account / status / postid

的字符串

我找到了一个检测@account的解决方案并创建了这样的链接:

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

但是,我需要正则表达式包含/status/postid并将其包含在链接中,最终输出应为:

<a href="http://www.twitter.com/account/status/postid" target="_blank">@account</a>

我曾尝试过(正如我所说,我完全迷失了,无法在网上找到解决方案):

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

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

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

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

修改

$ str的结构将是@TwitterAccountName / status / PostID

状态将始终为/ status /, TwitterAccountName和PostID

一样不同

超文本参考需要是twitter.com/TwitterAccountName/status/PostID

锚标记内的文本应该只是@TwitterAccountName

将字符串标识为需要链接到的Twitter页面的是@

1 个答案:

答案 0 :(得分:1)

如果您仍然对答案感兴趣,这应该可以解决问题:

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

与chris85类似,我不使用twitter,所以我不完全确定状态和postid所期望的字符串类型。我假设它们由“单词”字符组成(\w)。如果有必要,你当然可以改变它。

与我的正则表达式字符串的一个重要区别是,我将实际正则表达式与/|的不同字符分隔开,因为斜杠(/)必须一直被屏蔽(如\/),这非常繁琐(preg_replace接受任何字符作为正则表达式分隔符。)

我的测试字符串

$str='this is a test sentence with a @twaccount/twstatus/twpostid and some more words afterwards.'

变为:

'this is a test sentence with a <a target="_blank"
href="http://www.twitter.com/@twaccount/twstatus/twpostid"></a> 
and some more words afterwards.' // (no line breaks)

使用preg_replace()时,默认行为是替换搜索模式的所有出现。其他正则表达式版本中的g等全局标志不是必需的(并且会导致错误)。可以使用函数的可选第四个参数设置替换次数的限制。