PHP function to replace a (i)th-position character

前端 未结 5 1725
梦如初夏
梦如初夏 2020-12-03 10:20

Is there a function in PHP that takes in a string, a number (i), and a character (x), then replaces the character at position (i) with

5条回答
  •  孤街浪徒
    2020-12-03 10:43

    function replace_char($string, $position, $newchar) {
      if(strlen($string) <= $position) {
        return $string;
      }
      $string[$position] = $newchar;
      return $string;
    }
    

    It's safe to treat strings as arrays in PHP, as long as you don't try to change chars after the end of the string. See the manual on strings:

提交回复
热议问题