用标签替换Twitter用户名

时间:2012-02-05 20:39:29

标签: php regex

我想用{UserName}替换任何twitter @UserName。我现在有以下内容,用USER替换@username:

$string = "Tweet with @UserName in the string"
echo preg_replace('/@([a-z0-9_]+)/i', ' USER ', $tweet);

// Tweet with USER in the string

是否可以修改preg_replace以使其输出为

Tweet with {UserName} in the string

1 个答案:

答案 0 :(得分:1)

尝试

<?php
$string = "Tweet with @UserName in the string";

echo preg_replace('/\B@([a-z0-9_]+)/i', '{${1}}', $string);

注意:我添加了\ B,因此user@email.com之类的内容不会被替换。