PHP str_replace

前端 未结 7 2009
渐次进展
渐次进展 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条回答
  • 2021-01-25 11:17

    You could use preg_replace_callback():

    // as many as you think you'll need, maximum.
    // this can be programmatically generated, if need be
    $replacements = array('A', 'B', 'C', 'D', 'E', 'F', 'G'); // and so on    
    
    function get_replace_value($matches) {
        global $replacements;
        return array_shift($replacements);
    }
    
    $var = preg_replace_callback("/" + preg_quote($needle) + "/",
        "get_replace_value", $var);
    
    0 讨论(0)
  • 2021-01-25 11:26

    You could use preg_replace's limit argument to only replace once.

    <?php
        $var = 'X X X X';
        $replace = array('A', 'B', 'C', 'D');
        foreach($replace as $r)
            $var = preg_replace('/X/', $r, $var, 1);
        echo $var;
    ?>
    

    http://codepad.viper-7.com/ra9ulA

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-25 11:38

    Lots of loops are happening in the other answers, here's an alternative.

    $var = 'X X X X X X X';
    $replace = array('A', 'B', 'C', 'D');
    $var = preg_replace(array_fill(0, count($replace), '/X/'), $replace, $var, 1);
    echo $var; // A B C D X X X
    
    0 讨论(0)
  • 2021-01-25 11:39

    Without use of regex

    $arr = explode('X', 'X X X X');
    $rep = array('A','B','C','D');
    foreach ($arr as $idx=>$val)
    {
      $arr[$idx] = $val.$rep[$idx];
    }
    echo implode($arr);
    
    0 讨论(0)
  • 2021-01-25 11:42

    Yet one more solution (more for a dynamic number of Xs):

    <?php
    
      $foo = 'X X X X X X';
    
      $Xs = preg_match_all('/\bX\b/',$foo,$_); if ($Xs === false) $Xs = 0;
      $alphabet = range('A', chr(64 + $Xs));
      foreach ($alphabet as $letter){
        $foo = preg_replace('/\bX\b/', $letter, $foo, 1);
      }
    
      echo $foo;
    

    I also added the \b in to the pattern to only replace Xs that are free-standing, so "FAUX PAS X" only replaces the last X.

    demo

    alphabet_replace (more modular form)

    0 讨论(0)
提交回复
热议问题