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
Release: 2016-07-06 13:53:39
Original
1075 people have browsed it

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>
Copy after login

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

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template