我如何更改该正则表达式脚本
此正则表达式:
$text = preg_replace("/@([^\s]+)/", "<a href=\"\\0\">\\0</a>", $text);
.. 将以 @ 开头的所有单词转换为链接。所以它将 @joshua
变成:
<a href="@joshua">@joshua</a>..
但我需要它是:
<a href="joshua">@joshua</a>..
所以链接地址中没有 @
。谁能帮我解决这个问题吗?
This regex:
$text = preg_replace("/@([^\s]+)/", "<a href=\"\\0\">\\0</a>", $text);
.. transforms all words starting with @ into links. So it turns @joshua
into:
<a href="@joshua">@joshua</a>..
but I need it to be:
<a href="joshua">@joshua</a>..
so without the @
in the address of the link. Can anyone help me out with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注意:
[^\s]
可以缩写为\S
。注意:对于反向引用,
$0
优于\\0
(如 手动)。Note:
[^\s]
can be shortened to\S
.Note:
$0
is preferred over\\0
for backreferences (as stated in the manual).如果您阅读
preg_replace
文档,您会注意到\\0
是整个匹配,\\N
是第 N 个匹配。由于您已经捕获了名称(([^\s]+)
部分),因此您只需将\\0
:s 之一更改为\\1
。编辑:同样从文档中,您会看到从 PHP 4.0.4 开始,首选形式不是
\\N
,而是$N
。因此,如果您有最新(或者更确切地说,不是旧的)PHP 版本,则应将其更改为$0
和$1
。If you read the
preg_replace
documentation, you notice that\\0
is the entire match, and\\N
is the N:th match. Since you already capture the name (the([^\s]+)
part), you just need to change one of the\\0
:s to\\1
.EDIT: Also from the documentation, you'll see that from PHP 4.0.4, the preferred form is not
\\N
, but$N
. So, if you have a recent (or rather, not old) PHP version, you should change it into$0
and$1
.需要使用
\\1
来获取括号内的部分;\\0
是整个匹配。所以你需要的是You need to use
\\1
to get the part in parentheses;\\0
is the whole match. So all you need is这未经测试,但应该有效。
This is untested, but should work.