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