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?

 Answers

90
$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
 
toesslab
answered 9 Months ago
33

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

Wednesday, March 31, 2021
 
axiomer
answered 9 Months ago
18

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];
    else
        $newStr .= $shrapnel[$i] . rand(100,10000);
}
Wednesday, March 31, 2021
 
clean_coding
answered 9 Months ago
13

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 url.foo.com) 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 = ['differentsubdomain.foo.com', 'anotherplace.foo.com', 'someotherplace.foo.com'];
$random = $random_values[array_rand($random_values)];


$file = "https://url.foo.com/w_Path/SomeFile.ext";
$file = str_replace('url.foo.com', $random, $file);
  • Live demo at https://3v4l.org/um719

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 https://3v4l.org/X5KA3
Saturday, May 29, 2021
 
BradM
answered 7 Months ago
50

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
 
Kevin_Kinsey
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 :
 
Share