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

前端 未结 5 1700
梦如初夏
梦如初夏 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:31

    I amazed why no one remember about substr_replace()

    substr_replace($str, $x, $i, 1);
    
    0 讨论(0)
  • 2020-12-03 10:33
    implode(':', str_split('1300', 2));
    

    returns:

    13:00

    Also very nice for some credit card numbers like Visa:

    implode(' ', str_split('4900000000000000', 4));
    

    returns:

    4900 0000 0000 0000

    str_split — Convert a string to an array

    0 讨论(0)
  • 2020-12-03 10:38

    Codaddict is correct, but if you wanted a function, you could try...

    function updateChar($str, $char, $offset) {
    
       if ( ! isset($str[$offset])) {
           return FALSE;
       }
    
       $str[$offset] = $char;
    
       return $str;
    
    }
    

    It works!

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

    0 讨论(0)
  • 2020-12-03 10:44
    $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);
    
    0 讨论(0)
提交回复
热议问题