muaaz muaaz - 9 months ago 68
PHP Question

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


I had a longer solution


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;


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)]; }, 
echo $new;