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