我有一些字符串,我必须修复旧代码。我有这样的事情:
$str = 'a-b-x-d-e';
$str = 'bbbb-ccccc-y-ee-fff';
$str = 'aa-ee-z-jjjjjjjj-uuu';
$str = 'aa-ee-z-y-x';
中间的一个是(x或y或z)不再有效,我必须用“m,n或p”替换它
现在,有很多方法可以做到这一点,我想这样做:
$list = explode($str);
foreach($list as $k => $v) {
//find the third one and replace it by rebuilding the string
}
但这看起来很麻烦而且很长时间,有没有更快的方法?
编辑:我也可以在任何其他位置使用相同的值,这些值仍然有效。
答案 0 :(得分:1)
最简单的解决方案是使用str_replace。
$list = str_replace(array('x', 'y', 'z'), array('m', 'n', 'p'), $list);
这会将x
替换为m
,将y
替换为n
等。
$list
数组应该包含字符串列表。
这是键盘:http://codepad.org/mC602d7Z
这是基于x
y
和z
没有出现在其他地方的事实。
答案 1 :(得分:1)
这是一个简单的问题:
$str = 'a-b-x-d-e';
$newVar = 1;
$tmp = explode('-', $str);
$tmp[2] = $newVar;
$str = implode('-', $tmp);
unset($tmp);
echo $str;