preg_replace - 单独替换的数组
我正在努力实现以下目标:
$subject = 'ab a';
$search = 'a';
$替换='1';
:
期望的结果 数组
(
[0] => 1 乙
[1] => ab 1
) 有
什么办法可以用 preg_replace 实现这一点吗?
preg_replace('/\b'.$search.'(?=\s+|$)/u', $replace, array($subject));
将在同一结果中返回所有替换:
数组
(
[0] => 1 b 1
) 干杯
I am trying to achieve the following:
$subject = 'a b a';
$search = 'a';
$replace = '1';
Desired result:
Array
(
[0] => 1 b a
[1] => a b 1
)
Is there any way of achieving this with preg_replace?
preg_replace('/\b'.$search.'(?=\s+|$)/u', $replace, array($subject));
will return all the replacments in the same result:
Array
(
[0] => 1 b 1
)
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是不可能的。您可以在可选的第四个参数中指定替换限制,但始终从头开始。
使用
可以实现您想要的目标preg_split()
。您只需在搜索模式的所有情况下分割字符串,然后将它们一一弄乱。如果您的搜索模式只是一个简单的字符串,您可以使用explode()
实现相同的效果。如果您需要帮助找出这种方法,我将很乐意提供帮助。编辑:让我们看看这是否适合您:
注意:这尚未经过测试。请报告是否有效。
编辑2:
我现在用你的例子测试了它,修复了一些问题,现在它可以工作了(至少对于那个例子)。
I think it is not possible. You can specify a limit of replacements in the optional fourth parameter, but that always starts at the beginning.
It could be possible to achieve what you're looking for with
preg_split()
. You would just have to split your string on all occasions of your search pattern and then mess with them one by one. If your search pattern is just a simple string, you can achieve the same withexplode()
. If you need help figuring this approach out, I'll be happy to help.EDIT: Let's see if this works for you:
Note: This is not tested yet. Please report whether it works.
EDIT 2:
I tested it with your example now, fixed a few things and it works now (at least with that example).
输出
Output