Jump to content

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


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();
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.