如何使用PHP preg_replace链接Twitter用户名?

rho*_*son 4 php regex twitter preg-replace

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

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

但它没有做任何替换.我知道我的reg exp错了,但我无法确切地知道在哪里/为什么.救命?

**编辑:...按要求提供样本数据?

$text = '@janesmith I like that, but my friend @johndoe said it better.';
Run Code Online (Sandbox Code Playgroud)

期望的输出:

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

***** MY FULL FUNCTION *****

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;
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*rsH 5

为什么\之前有_?如果你取出它会有用\吗?虽然这不应该破坏功能......

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

此外,您可以简化:

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