Log in

View Full Version : replace the second char in a string.



james438
02-25-2008, 04:46 AM
How can I replace the second character in a string with another character?

james438
02-25-2008, 04:51 AM
sorry dumb question.


$string="blah"
$string=substr_replace($string,"",1,1);

boogyman
02-25-2008, 03:28 PM
sorry dumb question.

no such thing as a dumb question... you were just having a brain fart. glad you found the solution

djr33
02-25-2008, 10:31 PM
Though you found a better solution, you can always figure out something like this just using substr():
$a = $a[0].'X'.substr($a,2);
In fact, you might be able to just use: $a[1]='X';, but I'm not sure if that will cause any trouble with the variable type.

Leafy
02-26-2008, 12:16 AM
You can use brackets as if it were an array. After all, a string is really an array of characters with numerical indices.


$string[1] = ' ';

This replaces the 2nd letter of the variable "string" with a space.

james438
02-26-2008, 04:13 AM
those are some really interesting alternatives. I still plan on using the built in php function substr_replace(), but I really like the work around solutions both of you have posted.

alexjewell
02-27-2008, 06:22 PM
And here we find yet another beautiful thing about PHP: there's always so many ways to do things. :)