繁体   English   中英

php从字符串数组中替换所有出现的键

[英]php replace all occurances of key from array in string

也许这是重复的,但我没有找到好的解决方案。

我有阵列

$list = Array
(
   [hi] => 0
   [man] => 1
);
$string="hi man, how are you? man is here. hi again."

它应该产生 $final_string = "0 1, how are you? 1 is here. 0 again."

我该如何以聪明的方式实现它? 非常感谢。

从我的头顶上掉下来:

$find       = array_keys($list);
$replace    = array_values($list);
$new_string = str_ireplace($find, $replace, $string);

可以使用strtr()在一行中完成。

引用文档:

如果给定两个参数,则第二个参数应为array('from' => 'to', ...)形式的array('from' => 'to', ...) 返回值是一个字符串,其中所有出现的数组键都已被相应的值替换。 最长的键将首先尝试。 替换子字符串后,将不再搜索其新值。

要获取修改后的字符串,只需执行以下操作:

$newString = strtr($string, $list);

这将输出:

0 1, how are you? 1 is here. 0 again.

演示

preg_replace可能会有所帮助。

<?php
$list = Array
(
    'hi' => 0,
    'man' => 1
);
$string="hi man, how are you? Man is here. Hi again.";

$patterns = array();
$replacements = array();

foreach ($list as $k => $v)
{
    $patterns[] = '/' . $k . '/i';  // use i to ignore case
    $replacements[] = $v;
}
echo preg_replace($patterns, $replacements, $string);
$text = strtr($text, $array_from_to)

参见http://php.net/manual/en/function.strtr.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM