Guest User

Untitled

a guest
Oct 1st, 2012
392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.83 KB | None | 0 0
  1. <?php
  2.  
  3. $text = '{test|test2|test3} some other stuff {some1|some2|some3}';
  4.  
  5. $parser = new Parser($text);
  6. $parser->parse();
  7. for($i=0;$i<4;$i++)
  8.     echo $parser->replace().'<br />';
  9.  
  10. class Parser
  11. {
  12.     private $vars;
  13.     private $text;
  14.  
  15.     public function __construct($text)
  16.     {
  17.         $this->text = $text;
  18.         $this->vars = array();
  19.     }
  20.  
  21.     public function parse()
  22.     {
  23.         $pattern = '/\{([^}]+)\}/';
  24.         $matches = array();
  25.         preg_match_all($pattern, $this->text, $matches);
  26.  
  27.         $matches = array_shift($matches);
  28.  
  29.         foreach($matches as $match)
  30.         {
  31.             $this->vars[$match]= explode('|', str_replace(array('{', '}'), '', $match));
  32.         }
  33.  
  34.     }
  35.  
  36.     public function replace()
  37.     {
  38.         $text = $this->text;
  39.         foreach($this->vars as $k => $v)
  40.         {
  41.             $rand = rand(0, count($v)-1);
  42.             $text = str_replace($k, $v[$rand], $text);
  43.         }
  44.  
  45.         return $text;
  46.     }
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment