gpt4 book ai didi

php - 将关联数组与 preg_replace 结合使用

转载 作者:行者123 更新时间:2023-12-04 15:32:13 26 4
gpt4 key购买 nike

在 preg_replace 的文档中,它说您可以使用索引数组来替换多个字符串。我想用关联数组来做这个,但它似乎不起作用。

有谁知道这是否真的行不通?

最佳答案

您想对键或键和值执行此操作,还是只保留键并处理值?无论哪种情况,array_combine() , array_keys()array_values()可以结合起来实现这一目标。

按键上:

$keys = array_keys($input);
$values = array_values($input);
$result = preg_replace($pattern, $replacement, $keys);
$output = array_combine($result, $values);

关于键和值:

$keys = array_keys($input);
$values = array_values($input);
$newKeys = preg_replace($pattern, $replacement, $keys);
$newValues = preg_replace($pattern, $replacement, $values);
$output = array_combine($newKeys, $newValues);

关于值保留键:

$keys = array_keys($input);
$values = array_values($input);
$result = preg_replace($pattern, $replacement, $values);
$output = array_combine($keys, $result);

所有这些都假设了一个类似这样的函数:

function regex_replace(array $input, $pattern, $replacement) {
...
return $output;
}

关于php - 将关联数组与 preg_replace 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1987773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com