Ben*_*ton 3 php regex twitter preg-replace tweets
您好我需要在php中的推文中添加一个href标签,例如,如果我有这样的推文:
@username tweet body message http://t.co/sfr34s5
Run Code Online (Sandbox Code Playgroud)
我需要用php将其变成这个:
@username tweet body message <a href="http://t.co/sfr34s5">http://t.co/sfr34s5</a>
Run Code Online (Sandbox Code Playgroud)
我认为这可以使用preg_replace来完成,我有类似的东西已经在twitter @username周围包含一个链接,如下所示:
$tweet= preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $tweet);
Run Code Online (Sandbox Code Playgroud)
如何编辑此正则表达式部分,以便在出现的推文中围绕网址添加标记?
请尝试以下代码:
$source = '@username tweet body message http://t.co/sfr34s5';
$pattern = '/(http:\/\/[a-z0-9\.\/]+)/i';
$replacement = '<a href="$1" target="_blank">$1</a>';
$source = preg_replace($pattern, $replacement, $source);
Run Code Online (Sandbox Code Playgroud)
正则表达式将匹配以"http://"开头的所有字符串,后跟一系列字母数字值,正斜杠或点.
它应该适用于所有情况,但是,如果您只是尝试提取t.co链接,则可以使用此模式的更安全版本:
$pattern = '/(http:\/\/t\.co\/[a-z0-9]+)/i';
Run Code Online (Sandbox Code Playgroud)
这只会匹配'http://t.co/[alnum-chars].
如果需要匹配所有URL,则必须根据需要修改模式.例如,要匹配http://t.co/abcde?x=1&y=2,您需要使用以下模式:
$pattern = '/(http:\/\/[a-z0-9\.\/?=&]+)/i';
Run Code Online (Sandbox Code Playgroud)
我在PHP5.3上对此进行了测试,它使用了您指定的URL.
| 归档时间: |
|
| 查看次数: |
2170 次 |
| 最近记录: |