英文:
Strange behavior of str_replace
问题
我有一个用户可设置的文本,其中默认文本为“[登录]或[注册]以查看内容”。
我需要的是将这两个单词分别包含在它们各自的链接中。但首先,我需要检查用户是否更改了这个默认文本,换句话说,他们是否保留了方括号。我不会在检查这一点上花费太多时间。只要存在两组方括号就足够了。如果是这种情况,那么我会假设第一个链接是登录页面,第二个链接是注册账户页面...
所以,下面的if语句对我有用:
if ( preg_match( '/\[(.*?)\].*\[(.*?)\]/', $text ) )
然后,在if语句内部,我的计划是使用两个数组执行str_replace()
,就像这样:
$text = str_replace( array( '[', ']', '[', ']' ), array( '%1$s', '%2$s', '%3$s', '%4$s' ), $text );
但这并没有按照我想象的方式工作。我认为由于这两个数组具有相等数量的元素,它会进行一对一的搜索和替换,这意味着它会将文本变成%1$s登录%2$s或%3$s注册%4$s以查看内容
,但实际上它变成了%1$s登录%2$s或%1$s注册%2$s以查看内容
。
为什么会这样?如果这不是正确的做法(显然不是),我应该怎么做呢?
非常感谢您的帮助。TIA。
英文:
I have a user-settable text, where the default one is [Log in] or [register] to view the content
.
What I need, is to wrap the two words in square brackets in their respective links. But first, I need to check that the user didn't change this default text, in other words that they kept the square brackets. I won't go in great lengths in checking this. Just the existence of two sets of square brackets is enough. If that's the case, then I'll assume that the first link is for the login page, and the second is for the register-an-account page...
So, the if below does the job for me:
if ( preg_match( '/\[(.*?)\].*\[(.*?)\]/', $text ) )
Then, inside the if, my plan was to perform a str_replace()
with two arrays like this:
$text = str_replace( array( '[', ']', '[', ']' ), array( '%1$s', '%2$s', '%3$s', '%4$s' ), $text );
But this doesn't work the way I thought it would. I thought that since the two arrays have equal number of elements it'd do a 1-on-1 search and replace, meaning that it would turn the text to %1$sLog in%2$s or %3$sregister%4$s to view the content
, whereas it turned to %1$sLog in%2$s or %1$sregister%2$s to view the content
.
Why is that? If that's not the proper way to do that (which obviously isn't), what should I do instead?
Any help would be very much appreciated. TIA.
答案1
得分: 3
尝试使用preg_replace
与相同的模式(带有额外的捕获):
$text = preg_replace('/\[(.*?)\](.*)\[(.*?)\]/', '%1$s$1%2$s$2%3$s$3%4$s', $text);
这将产生以下结果:
%1$sLog in%2$s or %3$sregister%4$s to view the content
str_replace
不会按照你的意图工作 - 第一个数组是一个针对的数组,没有位置的概念,所以在你的情况下,第二组[]
是重复的针对。
查看tester。
英文:
Try using preg_replace
with your same pattern (with additional capture):
$text = preg_replace('/\[(.*?)\](.*)\[(.*?)\]/', '%1$s$1%2$s$2%3$s$3%4$s', $text);
which produces
%1$sLog in%2$s or %3$sregister%4$s to view the content
The str_replace does not work the way you intended - the first array is an array of needles which has no sense of position so the second set of []
are duplicate needles in your case.
See tester
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论