How can I add random character from [A-Za-z0-9]
/
or -
to a string every second character?
e.g.
input:
Hello_world!
output:
H3e7l2l-o2_aWmocr9l/db!s
Edit:
Here is what I’ve tried, however without the line below the one marked Here
that throws an error
Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in...
.
I guess it’s because a fragment of $char is not an array.
After I’d added the line below Here
to "convert" the string to array another error appeared:
Uncaught TypeError: str_repeat(): Argument #1 ($string) must be of type string, array given in...
<?php
$string = "Hello_World!";
$length = strlen($string);
$string = str_split($string, 2);
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/-";
//Here
$chars = (is_array($chars)) ? $chars : [$chars];
for($i = 0; $i < ($length / 2); $i++){
$char = substr(str_shuffle(str_repeat($chars, 1)), 0, 1);
$added = implode($string[$i], $char);
}
echo $string;
?>
3
Answers
str_split
splits your input string into characters, thenarray_reduce
recombines them with the random chars added.Since your inputs are both strings AND the pool of random characters contains only single-byte characters, this task can be directly achieved with no array functions and no concatenation.
Call for a random letter to be inserted in the original string after each letter via
preg_replace_callback()
.Code: (Demo)
K
tells the regex engine to forget the previously matched character. This results in no characters being lost — the random letter is added at the zero-width position after each character.If you were dealing with input arrays, then it might be worth reading Implode array with array of glue strings for a clever
vprintf()
trick.