1

我有以下内容:

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

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

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

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

请帮忙!

4

2 回答 2

3

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

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

工作示例

于 2013-11-06T23:46:10.447 回答
1

You can use a capturing group ( ) around your pattern you want captured to separate the captured match and the whole string. You can then place your captured match $1 where you desire and use $0 to access your whole string match.

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

You can use \S here instead. I don't recommend using \B inside of a negated character class.

Regular expression:

\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)

See a working demo

于 2013-11-06T23:55:24.597 回答