- preg_replace_callback: documentation ( source)
- array_rand: documentation ( source)
- explode: documentation ( source)
<?php
class Spintax
{
public static function Parse($text)
{
return self::Process($text);
}
private static function Process($text)
{
$pattern = '/\{(((?>[^\{\}]+)|(?R))*)\}/x';
return preg_replace_callback($pattern, ['Spintax', 'Replace'], $text);
}
private static function Replace($text)
{
$text = self::Process($text[1]);
$parts = explode('|', $text);
return $parts[array_rand($parts)];
}
}
$spintax = "{The|The actual|The particular|Your|This} breakthrough treatment {works by|functions|functions by|operates by|sticks to} oxygenating {the|the actual|the particular|your|this} blood {through an|with an|via an|using an|with the} injection {that can|that may|that will|which could|that could} hold {someone|somebody|an individual|a person|another person} alive {for up to|for approximately|for|for about|for as much as} 30 minutes {even if|even though|even when|regardless of whether|whether or not} they {are unable to|cannot|can't|can't seem to|are not able to} breath {at|from|with|in|on} everything {and could|and may|and might|and can|and may even} save {thousands of|a large number of|1000s of|a huge number of|many} lives.";
for($n = 0; $n < 20; $n++){
echo Spintax::Parse($spintax) . "\n";
}