基于索引的多字符串替换

时间:2013-11-22 05:55:04

标签: php string replace str-replace

我需要根据索引替换字符串的多个部分。

$string  = '01234567890123456789';

$replacements = array(
    array(3, 2, 'test'),
    array(8, 2, 'haha')
);

$expected_result = '012test567haha0123456789';

$replacements中的指数预计不会重叠。

我一直在尝试编写自己的解决方案,根据需要更换的部分将原始数组拆分成多个部分,最后将它们组合起来:

echo str_replace_with_indices($string, $replacements);
// outputs the expected result '012test567haha0123456789'

function str_replace_with_indices ($string, $replacements) {
    $string_chars = str_split($string);

    $string_sections = array();
    $replacing = false;
    $section = 0;
    foreach($string_chars as $char_idx => $char) {
        if ($replacing != (($r_idx = replacing($replacements, $char_idx)) !== false)) {
            $replacing = !$replacing;
            $section++;
        }
        $string_sections[$section] = $string_sections[$section] ? $string_sections[$section] : array();
        $string_sections[$section]['original'] .= $char;
        if ($replacing) $string_sections[$section]['new'] = $replacements[$r_idx][2];
    }

    $string_result = '';
    foreach($string_sections as $s) {
        $string_result .= ($s['new']) ? $s['new'] : $s['original'];
    }

    return $string_result; 
}

function replacing($replacements, $idx) {
   foreach($replacements as $r_idx => $r) {
       if ($idx >= $r[0] && $idx < $r[0]+$r[1]) {
           return $r_idx;
       }
   }
   return false;
}

有没有更有效的方法来达到同样的效果?

上述解决方案看起来并不优雅,并且对于更换字符串感觉很长。

1 个答案:

答案 0 :(得分:2)

使用此

$str = '01234567890123456789';
$rep = array(array(3,3,'test'), array(8,2,'haha'));
$index = 0;
$ctr = 0;
$index_strlen = 0;
foreach($rep as $s)
{
   $index = $s[0]+$index_strlen;

   $str = substr_replace($str, $s[2], $index, $s[1]);

   $index_strlen += strlen($s[2]) - $s[1];
}
echo $str;
相关问题