How do I change this function from Random to Sequential

Discussion in 'PHP' started by jeddiko, Oct 12, 2013.

  1. #1
    Hi,

    I am using this function which is
    used to spin text.

    Currently it looks to me like it is selected an
    element from the $tStringToken array at random.

    These two lines seem to be doing that:
    Expand|Select|Wrap|Line Numbers
    1. $i = rand(0,$tStringCount);
    2. $replace = $tStringToken[$i];
    I would like to change this so that it goes sequentially through
    all of the available elements in the array and then when finished
    starts again with the first element of the array.

    But I am having trouble working it out.

    This is the function I am working on.

    Expand|Select|Wrap|Line Numbers
    1. function spin($pass){
    2. $mytext = $pass;
    3. while(inStr("}",$mytext)){
    4. $rbracket = strpos($mytext,"}",0);
    5. $tString = substr($mytext,0,$rbracket);
    6. $tStringToken = explode("{",$tString);
    7. $tStringCount = count($tStringToken) - 1;
    8. $tString = $tStringToken[$tStringCount];
    9. $tStringToken = explode("|",$tString);
    10. $tStringCount = count($tStringToken) - 1;
    11. $i = rand(0,$tStringCount);
    12. $replace = $tStringToken[$i];
    13. $tString = "{".$tString."}";
    14. $mytext = str_replaceFirst($tString,$replace,$mytext);
    15. }
    16. return $mytext;
    17. }
    Any ideas on how I can do this would be very helpful

    Thanks.
     
    jeddiko, Oct 12, 2013 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    I'm a little drunk, but how's this?

    
    function spin($text)
    {
        static $calls = [];
      
        return preg_replace_callback('~\{([^\}]+)\}~', function (array $words) use (&$calls)
        {       
            $key = $words[0];
            $words = explode('|', $words[1]);
          
            if (!isset($calls[$key]))
            {
                $calls[$key] = 0;
            }
          
            return $words[$calls[$key]++ % sizeof($words)];
        }, $text);
    }
    
    PHP:
     
    nico_swd, Oct 12, 2013 IP