Home >Backend Development >PHP Tutorial >PHP replace matching parts of string with random items from an array?

PHP replace matching parts of string with random items from an array?

WBOY
WBOYOriginal
2016-07-06 13:53:391052browse

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

Reply content:

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).

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn