PHP str_replace

前端 未结 7 2012
渐次进展
渐次进展 2021-01-25 11:03

I have the string $var in which I need to replace some text. The first \"X\" needs to be replaced by \"A\", the second \"X\" needs to be replaced by B and so on, here is an exam

7条回答
  •  -上瘾入骨i
    2021-01-25 11:42

    Lets give it a shot, too, just for the heck of it ;)

    $input = "X X X X";
    
    function replace($input, array $replacements)
    {
        $replacer = function(array &$i, array &$r, &$o) use(&$replacer) {
            if (count($i) === 0 || count($r) === 0) return;
    
            $i_cur = array_shift($i);
    
            if (ctype_space($i_cur)) $o .= $i_cur;
            else $o .= array_shift($r);
    
            $replacer($i, $r, $o);
        };
    
        $replacer(str_split($input), $replacements, $output);
    
        return $output;
    }
    
    var_dump(replace($input, range('A', 'Z'))); 
    

提交回复
热议问题