views:

64

answers:

4

Hello all

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 it?

Thanks.

+8  A: 

You can just do:

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

as a function you can do:

function replaceithChar($str,$pos,$char) {
  if( ($pos >= 0) && ($pos < strlen($str)) && (strlen($char)==1) ) {
   $str[$pos] = $char;   
 }
 return $str;
}

or you could use the library function substr_replace (as pointed by konforce in the comments and zerkms in one of the answers) as:

$str = substr_replace($str,$char,$pos,1);
codaddict
Ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.substr
konforce
Damn! Beat me to it (the function) :P
alex
@codaddict - amazingly simple. Its a sin that I forgot that.
ShiVik
+3  A: 

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!

alex
+1  A: 
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:

Emil Vikström
+4  A: 

I amazed why no one remember about substr_replace()

substr_replace($str, $x, $i, 1);
zerkms
PHP - a function for everything!
alex
@alex: hehe ;-)
zerkms