从字符串中删除@符号

时间:2013-11-06 23:41:39

标签: php regex preg-replace

我有以下内容:

preg_replace('/\B@[^\B ]+/', '<a href="profile.php">$0</a>');

检查以@开头并以空格结尾并将其转换为链接的任何字符串。

现在我需要的是创建另一个preg_replace,它会从字符串中删除@符号,例如@hello,这样它就会变成hello

我需要这个,以便我可以将第一个preg_replace中的链接更改为<a href="profile.php?user=hello>$0</a>

请帮忙!

2 个答案:

答案 0 :(得分:3)

您可以在()中包含部分模式以创建新变量 在这种情况下,您的匹配字符串不含@ $ 1变量

preg_replace('/\B@([^\B ]+)/', '<a href="profile.php?profile=$1">$0</a>');

Working example

答案 1 :(得分:1)

您可以在希望捕获的模式周围使用捕获组( )来分隔捕获的匹配项和整个字符串。然后,您可以将捕获的匹配$1放在所需的位置,并使用$0来访问整个字符串匹配。

preg_replace('/\B@(\S+)/', '<a href="profile.php?profile=$1">$0</a>', $str);

您可以在此处使用\S。我不建议在否定的字符类中使用\B

正则表达式:

\B            the boundary between two word chars (\w) 
              or two non-word chars (\W)
 @            '@'
\S+           non-whitespace (all but \n, \r, \t, \f, and " ") (1 or more times)

查看working demo