3

I want to replace every number in a string like ABC123EFG with another random char.
My idea was to generate a random string with the number of all numbers in $str and replace every digit by $array[count_of_the_digit], is there any way to do this without a for-loop, for example with regex?

$count = preg_match_all('/[0-9]/', $str);
$randString = substr(str_shuffle(str_repeat("abcdefghijklmnopqrstuvwxyz", $count)), 0, $count);
$randString = str_split($randString);
$str = preg_replace('/[0-9]+/', $randString[${n}], $str); // Kinda like this (obviously doesnt work)
2
  • I can't think of any way you're going to get a string of random characters without a loop. Why don't you want to use a loop? (Is it just me, or does it sometimes seem like there's someone telling new programmers that loops are bad?) Commented Mar 15, 2017 at 17:07
  • Its not that loops are bad, it just seems that this can be done a lot more cleanly with regex or something similiar Commented Mar 15, 2017 at 17:12

2 Answers 2

5

You could use preg_replace_callback()

$str = 'ABC123EFG';

echo preg_replace_callback('/\d/', function(){
  return chr(mt_rand(97, 122));
}, $str);

It would output something like:

ABCcbrEFG

If you want upper case values, you can change 97 and 122 to their ASCII equivalent of 64 to 90.

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to do this in python?
0

You can use preg_replace_callback to call a function where the returned value is the replacement. Here is an example that does what you want:

<?php
function preg_replace_random_array($string, $pattern, $replace){
    //perform replacement
    $string = preg_replace_callback($pattern, function($m) use ($replace){
            //return a random value from $replace
            return $replace[array_rand($replace)];
        }, $string);

    return $string;
}

$string = 'test123asdf';

//I pass in a pattern so this can be used for anything, not just numbers.
$pattern = '/\d/';
//I pass in an array, not a string, so that the replacement doesn't have to
//be a single character. It could be any string/number value including words.
$replace = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');

var_dump(preg_replace_random_array($string, $pattern, $replace));

1 Comment

array_flip(range('A', 'Z'))?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.