<?php
/**
* Callback function for preg_replace_callback
* Randomly return one word in list
*
* @param Array $match matched result from preg_replace_callback pattern
* @return String random word in list
*/
function spin_replace_callback($match)
{
$words = explode('|', $match[1]);
return $words[array_rand($words)];
}
/**
* Process each spin block in string
*
* each block must start with "{" and end with "}"
* separate each word with "|"
*
* eg. {hello|hi} {everyone|everybody}
*
* @param String $text string to process spin text block
* @return String spin result
*/
function process_spin_block($text)
{
return preg_replace_callback('~\{(.*?)\}~', 'spin_replace_callback', $text);
}วิธีใช้
<?php
echo process_spin_block('{Hello|Hi} {everyone|everybody}. Do you know {who|what} am i ?');