I have a sentence that needs to randomly change parts that are in the curly braces. The important part is that the values inside the braces can change (as in you could put any word in there), so
$x = '{Please,|Just|If you can,} make so, that this
{incredible|cool|simple|important|useless} sentence {fast|correctly|instantly}
changed randomly every time'; //this is the string that needs to be broken up
When I use
$parts = explode('{', $x);
it gives me an array that looks like this
array ([0]=>[1]=>{Please,|Just|If you can,} make so, that this [2]=>incredible|cool|simple|important|useless} sentence [3]=>fast|correctly|instantly} changed randomly every time)
which doesn't work.
What I've done is:
$parts = [
['Please,','Just','If you can,'],
['incredible', 'cool','simple','important','useless'],
['fast','correctly','instantly'],
];
$p = [];
foreach ($parts as $key => $values) {
$index = array_rand($values, 1);
$p[$key] = $values[$index];
}
$x_one = $p[0] . ' make it so that ' . $p[1] . ' this sentence
changed ' . $p[2] . ' randomly every time.';
echo $x_one;
I have to get $parts from $x, because the words in the string $x can change. Don't know where to go from here.
You can use preg_replace_callback() to catch the sequence, split using | and return a random value:
$x = '{Please,|Just|If you can,} make so, that this
{incredible|cool|simple|important|useless} sentence {fast|correctly|instantly}
changed randomly every time';
// catch all strings that match with {...}
$str = preg_replace_callback('~\{([^}]+)\}~', function($matches){
// split using |
$pos = explode('|', $matches[1]);
// return random element
return $pos[array_rand($pos)];
}, $x);
echo $str;
Possible outputs:
Regular expression:
\{ # { character
( # capture group
[^}]+ # all character until }
) # end capture group
\} # } character
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With