Reputation: 2249
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
Make me cumm.... mmmm Phones going to
Make me cumm.... mmmm Phone's going to
Make me cum.... mmmm Phones going
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
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