Alright, Say I have $string = "000000000000000000000"; And I need to replace the 3rd 0 in with a 1, resulting in "001000000000000000000" How would I do this? str_replace won't work because it replaces all 0's obviously, and using sub_str with str_replace like: str_replace(substr($string, $click2, $click3), "1", $string); Replaces it with all 1's, so it doesn't work either Thanks for the help!
Is it always the 3rd character? You can use 2 substr's and rejoin them with the new character. $string = "000000000000000000000"; $string1 = substr($string,0,2); $string2 = substr($string,4); $new_string = $string1 . '1' . $string2; Or combined: $new_string = substr($string,0,2) . '1' . substr($string,4);
Not always third, the number will be from user input, I see what you mean though, I cant set the numbers as vars. I'll mess with it a bit. Thanks.
You can also try something like this. You can reference a string's character position as an array. Basically: $string = "000000000000000000000"; echo $string; //000000000000000000000 $string[2] = 'p'; echo $string; //00p000000000000000000 The first character is [0], and so on. Probably easier than substr anyway.
Try this function: function replace_character($string, $index, $newchar){ $before = substr($string, 0, $index - 1); $after = substr($string, $index, strlen($string)); return $before.$newchar.$after; } echo replace_character("000000000000000000000", 3, "1"); PHP: This Prints: 001000000000000000000
or if you want to use jestop method: function replace_character($string, $index, $newchar){ $string[$index-1] = $newchar; return $string; } echo replace_character("000000000000000000000", 3, "1"); PHP:
I think you can only replace at the beginning or end, or add in the middle with substr_replace. As far as I know, you can't replace in the middle. Disregard, was thinking of something else. Just checked the manual and it should work fine.