Alex Rivera | Logout

Replace or insert characters into a string based on a numeric position in the string

Asked 2010-10-22T06:02:36.023
33

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 (x)?

If not, can somebody help me in implementing a function which can replace or insert a substring?

Edit
Report

1 Answer

1
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:

answered 2010-10-22T06:09:13.517

Your Answer