php String Shuffler

ii silver ii

ǝɹıɟpǝʞɔı&
Dec 18, 2008
767
23
0
This probably already exists but I can't think what to search for or how to code it at the moment, basically enter a paragraph of text into a form input then wherever it sees:

Code:
{keyword1|keyword2|keyword3}

It will just echo one of those words randomly?

I'm guessing it would use preg_match with some sort of random array shuffle but my minds gone blank..
 


If you know the delimiter is '|' and the number of words per expression is relatively small you can use:
PHP: explode - Manual

get the resulting array size and echo a random index in that range (0, count($arr)-1).
 
  • Like
Reactions: ii silver ii
For anyone that wants to use this...

The only thing it doesn't do is give all possible results which would be very useful, any ideas?

Code:
<?
if($comment = $_POST[comment])
{		
	$words = explode(" ", $comment);
	$shuffledComment;
	
	foreach ($words AS $singleWord)
	{			
		if(preg_match_all("~{(.*?)}~s", $singleWord, $match))
		{
			$resCount = count($match);
						
			foreach ($match[1] AS $single)
			{
				$matchKeyword = explode("|", $single);
				$rand = rand(0, (count($matchKeyword) - 1));
				$singleWord = $matchKeyword[$rand];
			}
		}

		$shuffledComment .= $singleWord." ";
	}
}
?>
<form action="" method="post">
	<textarea id="comment" name="comment" cols="80" rows="14"><?=$_POST[comment]?></textarea><br /><br />
<?
if($_POST)
{
?>
	<textarea id="commentNew" name="commentNew" cols="80" rows="14"><?=$shuffledComment?></textarea><br /><br />
<?
}
?>
	<input name="" type="submit" value="Create Comments" />
</form>
 
Code:
function spin($s){
   preg_match('#\{(.+?)\}#is',$s,$m);
   if(empty($m)) return $s;

   $t = $m[1];

   if(strpos($t,'{')!==false){
      $t = substr($t, strrpos($t,'{') + 1);
   }

   $parts = explode("|", $t);
   $s = preg_replace("+\{".preg_quote($t)."\}+is", $parts[array_rand($parts)], $s, 1);

   return spin($s);
}

//Example:
echo spin('{This|Here} is {some|a {little|wee|short} bit of} {example|demo|sample} text.');

That will handle nested as well.
 
  • Like
Reactions: ii silver ii
That's great thanks, the only other thing would be to return all possible comment values which I guess would be pretty tricky as you don't know how many nested values would be used etc..