String 替换php中相同位置的字符串
我有一些字符串需要从旧代码中修复。我有这样的想法:String 替换php中相同位置的字符串,string,replace,position,String,Replace,Position,我有一些字符串需要从旧代码中修复。我有这样的想法: $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
$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
}
但这似乎非常繁琐和漫长,有没有更快的方法
编辑:我也可以在任何其他位置使用相同的值,这些值仍然有效。最简单的解决方案是使用 这将用
m
替换x
,y
替换n
等
$list
数组应该包含字符串列表
这是代码板:
这是基于这样一个事实,即x
y
和z
不会出现在其他任何地方。这里有一个简单的例子:
$str = 'a-b-x-d-e';
$newVar = 1;
$tmp = explode('-', $str);
$tmp[2] = $newVar;
$str = implode('-', $tmp);
unset($tmp);
echo $str;
$str = 'a-b-x-d-e';
$newVar = 1;
$tmp = explode('-', $str);
$tmp[2] = $newVar;
$str = implode('-', $tmp);
unset($tmp);
echo $str;