Help me write this function?

Hey guys, being a bit of a novice at PHP I’m struggling with this function.
I want to choose a random word inside the {} to make a different sentence each time I reload my page. The “|” separates each word

I don’t think its a lot of code but could someone help me or point me in the right direction? I was hoping someone had made similar but cant seem to find any php code on the net.


<?php
$text = "The {quick|slow|reasonably paced} {brown|green|blue|pink} {fox|goat|rat|camel}
{jumped|walked|hopped} {over|past|under} the {lazy|tired|boring} {dog|cat|stoat}";

echo Spin($text);
}
?>


<?php
error_reporting(-1);
ini_set('display_errors', true);

$text = "The {quick|slow|reasonably paced} {brown|green|blue|pink} {fox|goat|rat|camel}
{jumped|walked|hopped} {over|past|under} the {lazy|tired|boring} {dog|cat|stoat}";

function spin($text){
  return preg_replace_callback(
    '~{([^}]+)}~',
    create_function(
      '$match',
      '$possible = explode("|", $match[1]); return $possible[array_rand($possible)];'
    ),
    $text
  );
}

echo spin($text);

?>

hey guys sorry for the late reply, going try this code out now…

Thanks a lot for your help

I have a similar question
What if the sentence is this:


<?php

$rand_sentence = "{Please|Just} make this {cool|awesome|random} test sentence {rotate {quickly|fast} and random|spin and be random}";

just one thing, the text in question was just example… the words outside the {} could be anything. How would i change the code to allow any text? I’m just working through the man to see how it works :slight_smile:

Thanks for your time.

Solved:


<?php

function ran($text)
{
  return preg_replace_callback(
    '~{(?:([^{}]+|\\{(?1)\\})*)}~',
    create_function(
      '$match',
      '$possible = explode("|", $match[1]);
	   return $possible[array_rand($possible, 1)];'
    ),
    $text
  );
}

It might be a better way to do this, so don’t be shy.

I love you so much! in a manly kinda way lol works a treat :slight_smile:


function displayQuickBrownFox(){
	$text = "The {quick|slow|reasonably paced} {brown|green|blue|pink} {fox|goat|rat|camel} {jumped|walked|hopped} {over|past|under} the {lazy|tired|boring} {dog|cat|stoat}";
	$x = preg_match_all('/{([a-z\\| ]+)}/i',$text,$matches);
	$xx = $matches[0];
	for($i=0; $i<count($matches[0]); $i++){
		$y = explode('|',preg_replace('/{|}/','',$matches[0][$i]));
		$z = array_rand($y);
		$matches[0][$i] = $y[$z] . ($i == (count($matches[0])-3) ? ' the ' : '');
	}
	return 'The ' . implode(' ',$matches[0]);
}
echo displayQuickBrownFox();

sample
http://www.rnel.net/code-snippets/quick_brown_fox.php

let me know if you need the explanation :slight_smile: