PHP str_replace

前端 未结 7 2019
渐次进展
渐次进展 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:27

    $var = 'X X X X';
    $replacements = array('A', 'B', 'C', 'D');
    
    $var = preg_replace_callback('/X/', function() use (&$replacements) {
        return array_shift($replacements);
    }, $var);
    

    Other solution:

    $var = preg_replace('/X/', 'A', $var, 1);
    $var = preg_replace('/X/', 'B', $var, 1);
    $var = preg_replace('/X/', 'C', $var, 1);
    $var = preg_replace('/X/', 'D', $var, 1);
    

    This one uses the $limit parameter of preg_replace (we replace only one occurrence per call).

提交回复
热议问题