Home >Backend Development >PHP Tutorial >PHP replace matching parts of string with random items from an array?
Thanks for your attention.
For example, the array is ['aaa','bbb','ccc']
and the string is "abadf@@@kjasf@@@jlasfkj@@@akfsdj@@@adskjdfda@@@sjdfas
"
. Replace the "@@@
" with random items in the array. The result is, for example,
abadfaaakjasfcccjlasfkjaaaakfsdjbbbadskjdfdaaaasjdfas
or
abadfccc kjasfaaajlasfkjaaaakfsdjcccadskjdfdabbbsjdfas
Thanks for your attention.
For example, the array is ['aaa','bbb','ccc']
and the string is "abadf@@@kjasf@@@jlasfkj@@@akfsdj@@@adskjdfda@@@sjdfas
"
. Replace the "@@@
" with random items in the array. The result is, for example,
abadfaaakjasfcccjlasfkjaaaakfsdjbbbadskjdfdaaaasjdfas
or
abadfccc kjasfaaajlasfkjaaaakfsdjcccadskjdfdabbbsjdfas
You try this method, I just wrote it casually and haven’t tested it yet. Can you try it?
<code>function getStringReplace($array, $string){ $result = ''; $stringArray = explode("@@@", $string); foreach($stringArray as $value){ $val = array_rand($array, 1); $result .= $value.$val; } echo $result; }</code>
First use the array_rand
function to randomly select a unit from the array, and then replace it with the preg_replace
function (note that the limit parameter = 1).