使用数组调用 preg_replace() 之前需要 ksort() 吗?啊?
周末我在使用 preg_replace
进行了一些工作,并且正在阅读 Php preg_replace
文档 当我看到一些奇怪的东西时。
文档中的示例 #2 显示,当给出以下 php 代码时,
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>
输出将是
"The bear black slow jumped over the lazy dog."
,为了生成默认情况下应该输出的内容(在我看来),我需要事先调用 ksort()
。像这样:
<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>
这真的不是 php preg_replace()
中错误的解决方法吗?为什么 php 会有这样的行为?此处声明的数组是否有一些我缺少的特质?
I was working a bit with preg_replace
over the weekend and I was reading the Php preg_replace
documentation when I saw something odd.
Example #2 from the docs shows that when given the following php code
<?php
$string = 'The quick brown fox jumped over the lazy dog.';
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>
the output will be
"The bear black slow jumped over the lazy dog."
and in order to generate what (in my opinion) should be output by default I would need to call ksort()
beforehand. like this:
<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>
Isn't this really a work-around for a bug in php's preg_replace()
? Why does php behave this way? Is there some idiosyncrasy with the arrays declared here that I am missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
文档还说:
因此发生这种情况的原因是使用了简单的
foreach
类型迭代,而不是索引访问。the docs also say:
So the reason it happens is that simple
foreach
-type iteration is used and not index access.遗憾的是,PHP 中的所有数组都是关联数组。
存储为
2->熊,1 ->黑色,0 ->慢
而不是典型的慢块
|黑色|熊
Sadly, all arrays in PHP are associative arrays.
Is stored as
2 -> bear, 1 -> black, 0 -> slow
Instead of the typical blocks of
slow | black | bear
数组索引就是这样,索引,它们不指示值在内存中存储的位置,像 next() 和 current() 这样的函数,我想象 preg_replace 在传递数组时使用它们,从起始内存地址迭代数组到最后为了效率。
与 php 中的很多东西一样,这个数组迭代是为了速度而构建的,其他任何事情都完全取决于开发人员,这就是为什么你必须添加更多行来完成稍微多一点的工作。
Array indices are just that, indices, they don't dictate where in memory the values are stored, functions like next() and current() which i imagine preg_replace uses when passed arrays, iterate over the array from the starting memory address to the last for efficiency.
As with alot of things in php, this array iteration is built for speed, anything else is quite rightly up to the developer, which is why you have to add a couple more lines to do slightly more work.
preg_replace()
的行为就像它执行这样的代码一样,我希望该函数在不调用
ksort()
的情况下也能正常工作。preg_replace()
behaves like if it would be executing code like thisI would have preferred the function would have worked without to call
ksort()
.