Asked  9 Months ago    Answers:  5   Viewed   55 times

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?


$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);
Wednesday, March 31, 2021
answered 9 Months ago

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)

Wednesday, March 31, 2021
answered 9 Months ago

I don't think you can do this using any of the search and replace functions, so you'll have to code up the replace yourself.

It looks to me like this problem works well with explode(). So, using the example token generator you provided, the solution looks like this:

$shrapnel = explode('%%token%%', $str);
$newStr = '';
for ($i = 0; $i < count($shrapnel); ++$i)  {
    // The last piece of the string has no token after it, so we special-case it
    if ($i == count($shrapnel) - 1)
        $newStr .= $shrapnel[$i];
        $newStr .= $shrapnel[$i] . rand(100,10000);
Wednesday, March 31, 2021
answered 9 Months ago

Put the values you randomly want to select into an array, use array_rand() to pick a random element (this returns the key, so you have to select the value from the array again based on the key you got), then use str_replace() to replace the value.

If the search-string ("needle", in your case is not found, no replacement will happen. Beware, that this will replace all instances of that needle if it occurs more than once.

$random_values = ['', '', ''];
$random = $random_values[array_rand($random_values)];

$file = "";
$file = str_replace('', $random, $file);
  • Live demo at

You can also use array_flip(), and use array_rand() on that to achieve the same result.

$random = array_rand(array_flip($random_values));
  • Live demo of that at
Saturday, May 29, 2021
answered 7 Months ago

Try mb_convert_encoding() with the "to" encoding as 'HTML-ENTITIES', and (if necessary) the "from" encoding set to 'UTF-8' or whichever Unicode encoding you're using.

Thursday, July 29, 2021
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :