Muaaz Khalid
Muaaz Khalid

Reputation: 2249

PHP: String manipulation choose random

I have the following string

Make me {cum|cumm}.... mmmm {Phones|Phone's} {gonna|going to|going}

There are some roles.

the text within curly brackets has one pipe Sign "|". means, either of two values.

If we take {Phone|Phone's} I want to choose one of them randomly and it can have more than two or three values or even a single value in curly brackets.

So the above string can result one of the following

  1. Make me cumm.... mmmm Phones going to

  2. Make me cumm.... mmmm Phone's going to

  3. Make me cum.... mmmm Phones going

  4. Make me cumm.... mmmm Phone's going to

Update

I had a longer solution

preg_match_all("~\{(.*?)\}~",$string,$matches);

    foreach($matches[1] as $match) {
        $options = explode("|", $match);
        if(count($options) > 0) {
            $key = array_rand($options);
            $randomValue = $options[$key];

            $string = str_replace("{".$match."}", $randomValue, $string);
        }
    }

    return $string;

Upvotes: 0

Views: 60

Answers (1)

splash58
splash58

Reputation: 26153

Use preg_replace_callback function, split matches, and take an random element of the resulting array

$new = preg_replace_callback('/{([^}]+)}/', 
                             function($i) { 
                               $t = explode('|', $i[1]); 
                               return $t[array_rand($t)]; }, 
                             $string);
echo $new;

Upvotes: 3

Related Questions