如何使用 PHP preg_replace 链接 Twitter 用户名? [英] How do I linkify Twitter usernames using PHP preg_replace?

查看:18
本文介绍了如何使用 PHP preg_replace 链接 Twitter 用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想搜索我的 twitter 状态对象的 text 属性并将@username 换成 <a href="http:/twitter.com/username">@username</a>.到目前为止我尝试过的看起来像这样:

I want to search the text property of my twitter status objects and swap out @username for <a href="http:/twitter.com/username">@username</a>. What I have tried so far looks like this:

$pattern = '/([@]{1})([a-zA-Z0-9\_]+)/';
$replace = '<a href="http://twitter.com/\2">\1\2</a>';
$new_string = preg_replace($pattern, $replace, $text);

但它不做任何替换.我知道我的 reg exp 是错误的,但我不知道确切的位置/原因.帮助?

But it doesn't do any replacements. I know my reg exp is wrong but I can't figure out exactly where/why. Help?

**...如要求的样本数据?

** ... sample data as requested?

$text = '@janesmith I like that, but my friend @johndoe said it better.';

期望的输出:

@janesmith 我喜欢这样,但我的朋友 @johndoe 说得更好.

@janesmith I like that, but my friend @johndoe said it better.

***** 我的全部功能 *****

function linkify($string, $twitter=false) {

    // reg exp pattern
    $pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

    // convert string URLs to active links
    $new_string = preg_replace($pattern, "<a href=\"\\0\">\\0</a>", $string);

    if ($twitter) {
        $pattern = '/@([a-zA-Z0-9_]+)/';
        $replace = '<a href="http://twitter.com/\1">@\1</a>';
        $new_string = preg_replace($pattern, $replace, $new_string);
    }

    return $new_string;
}

推荐答案

为什么 \_ 之前?如果你把\ 去掉,它会起作用吗?虽然这不应该破坏功能......

Why is the \ there before _? Does it work if you take out the \? Though that shouldn't have broken the functionality...

\1 更改为 \\1 可能会有所帮助,以便您确定反斜杠已转义;或更好(自 PHP 4.0.4 起)$1.但同样,它应该在单引号内按原样工作.

It might be helpful to change the \1 to \\1 so that you're sure the backslash is escaped; or better (since PHP 4.0.4) $1. But again, it should have worked as-is, within single quotes.

此外,您还可以简化:

$pattern = '/@([a-zA-Z0-9_]+)/';
$replace = '<a href="http://twitter.com/$1">@$1</a>';

这篇关于如何使用 PHP preg_replace 链接 Twitter 用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆