在 preg_replace 函数期间删除字符
我需要从字符串中提取一些文本,然后用在一个实例中而不是在另一个实例中删除的字符替换该文本。希望这个例子能告诉你我的意思(这是我到目前为止所得到的):
$commentEntry = "@Bob1990 I think you are wrong...";
$commentText = preg_replace("/(@[^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=${1}$1\">$1</a>", $commentEntry);
我希望结果是:
<a href="http://www.youtube.com/comment_search?username=Bob1990">@Bob1990</a> I think you are wrong...
但是我得到:
<a href="http://www.youtube.com/comment_search?username=@Bob1990">@Bob1990</a> I think you are wrong...
我已经在这个问题上工作了至少一个小时,几乎放弃了希望,所以非常感谢任何帮助!
I need to extract some text from a string, then replace that text with a character removed in one instance and not in another. Hopefully this example will show you what I mean (this is what I have so far):
$commentEntry = "@Bob1990 I think you are wrong...";
$commentText = preg_replace("/(@[^\s]+)/", "<a target=\"_blank\" href=\"http://www.youtube.com/comment_search?username=${1}$1\">$1</a>", $commentEntry);
I want the result to be:
<a href="http://www.youtube.com/comment_search?username=Bob1990">@Bob1990</a> I think you are wrong...
But am getting:
<a href="http://www.youtube.com/comment_search?username=@Bob1990">@Bob1990</a> I think you are wrong...
I have been working on this one problem for at least an hour and nearly given up hope, so any help is greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以尝试这样的事情
could try something like this
您可以做的是调整捕获。将
@
从大括号中移出:然后您可以编写替换字符串,例如
注意第一个
$1
如何重新插入文本,第二个$1
> 以逐字@
为前缀以将其重新输入。What you can do is adapt the capturing. Move the
@
out of the braces:Then you can write your replacement string like
Note how the first
$1
just reinserts the text, and the second$1
is prefixed by a verbatim@
to get it back in.您正在捕获模式中的
@
,因此当您使用$1
时它将始终输出。试试这个:这里的区别是
@
不再被捕获为$1
的一部分(即它只会捕获 Bob1990。由于它是一个文字值,所以它不会不需要成为任何模式的一部分。相反,我只是将其更改为在元素文本中直接在捕获的名称之前输出(即它现在是@$1
而不仅仅是$1
)。You're capturing the
@
in your pattern, so it'll always be output when you use$1
. Try this instead:The difference here is that the
@
is no longer captured as part of$1
(i.e. it'll capture only Bob1990. Since it's a literal value, it doesn't need to be part of any pattern. Instead, I just changed it to output as a literal value in the element text, directly before the captured name. (i.e. it now does<a>@$1</a>
rather than just<a>$1</a>
).