Php 用标签替换Twitter用户名

Php 用标签替换Twitter用户名,php,regex,Php,Regex,我想用{UserName}替换任何twitter@UserName。我现在有以下内容,将@username替换为USER: $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

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

$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
?试试看

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

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

重读你的笔记:不应该写电子邮件地址吗?这只是我在寻找的用户名:)你是对的,它省略了它,但我想写的是不会被替换,但不会被忽略。顺便说一句,我正在尝试实现您对用户名和hashtags所做的操作。我想删除所有的#,所以“我爱#atwt”应该替换为“我爱atwt”:preg#u replace('/#[^\s]*/I','${1}',$string)。但是,这只返回空括号({})。你能解释一下为什么吗?它返回空括号,因为正则表达式中没有任何捕获。捕获是包含在
()
中的模式。在实际单词的周围加上它,然后
${1}
将在替换中起作用。