Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Getting values from an array/random word generator/split string into an array

Tags:

arrays

php

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.

like image 340
Anna Kurmanova Avatar asked Jul 25 '26 20:07

Anna Kurmanova


1 Answers

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:

  • If you can, make so, that this cool sentence correctly changed randomly every time
  • Please, make so, that this cool sentence fast changed randomly every time
  • If you can, make so, that this incredible sentence fast changed randomly every time

Regular expression:

\{       # { character
 (       # capture group
 [^}]+   # all character until }
 )       # end capture group
\}       # } character
like image 110
Syscall Avatar answered Jul 28 '26 09:07

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!