phpstringreplacesubstring

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


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?


Solution

  • $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);