Jump to content

How can I get str_replace to replace all instances with a changing replacement?


physaux

Recommended Posts

Ok so, I am trying to replace all instances of "%" with a random character. I first tried this:

 

$realoutput = str_replace("%",randomchar(),$realoutput);

 

randomchar() is a custom function I have. My problem is that it replaces the % with only 1 result of "random char()". So with 12%12%12% I get 12R12R12R or 12P12P12P instead of something like 12O12Y12N.

 

Any suggestions how I can get the result that I want? I can't seem to figure it out! :confused: :confused:

you could loop through each character if cpu usage isnt' a big deal

 


<?php

for ( $i = 0; $i < strlen($String), $i++ )
{
$Byte = substr($String, $i, 1); //takes one character
$NewString .= str_replace("%",randomchar(),$Byte);
}

 

Why str_replace() on 1 character? Just compare it and change it, like

 

$Byte = substr($String, $i, 1); //takes one character
$NewString .= '%' === $Byte ? randomchar() : $Byte;

 

Or something like:

 

$char = '%';
$string = '12%12%12';

$pos = -1;
while (true) {
  $pos = strpos($string, $char, $pos + 1);
  if (false === $pos) break;
  
  $string[$pos] = randomchar();
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.