Replace character's position in a string

后端 未结 4 838
小蘑菇
小蘑菇 2020-12-21 12:37

In PHP, how can you replace the second and third character of a string with an X so string would become sXXing?

The string\'s

相关标签:
4条回答
  • 2020-12-21 13:18

    Simple:

    <?php
    $str = "string";
    $str[1] = $str[2] = "X";
    echo $str;
    ?>
    
    0 讨论(0)
  • 2020-12-21 13:23

    For replacing, use function

    $str    = 'bar';
    $str[1] = 'A';
    echo $str; // prints bAr
    

    or you could use the library function substr_replace as:

    $str = substr_replace($str,$char,$pos,1);
    

    similarly for 3rd position

    0 讨论(0)
  • 2020-12-21 13:33

    It depends on what you are doing.

    In most cases, you will use :

    $string = "string";
    $string[1] = "X";
    $string[2] = "X";
    

    This will sets $string to "sXXing", as well as

     substr_replace('string', 'XX', 1, 2);
    

    But if you want a prefect way to do such a cut, you should be aware of encodings.

    If your $string is 我很喜欢重庆, your output will be "�XX很喜欢" instead of "我XX欢重庆".

    A "perfect" way to avoid encoding problems is to use the PHP MultiByte String extension.

    And a custom mb_substr_replace because it has not been already implemented :

    function mb_substr_replace($output, $replace, $posOpen, $posClose) {
        return mb_substr($output, 0, $posOpen) . $replace . mb_substr($output, $posClose + 1);
    }
    

    Then, code :

    echo mb_substr_replace('我很喜欢重庆', 'XX', 1, 2);
    

    will show you 我XX欢重庆.

    0 讨论(0)
  • 2020-12-21 13:38
    function mb_substr_replace($string, $replacement, $start, $length=0)
    {
        return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start+$length);
    }
    

    same as above, but standardized to be more like substr_replace (-substr- functions usually take length, not end position)

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