PHP Spinning Syntax

Discussion in 'PHP' started by nickharper, Mar 25, 2010.

  1. #1
    At the minute I am able to spin articles but I have to create a list of arrays for certain words and then echo a random word from the array to give a spun effect.

    How would I go about in PHP making it so that if I just put in the following it would spin the text?

    "I wear a {yellow|green|blue} {coat|jacket|T shirt}"

    I have looked on the net but can't seem to find anything.
     
    nickharper, Mar 25, 2010 IP
  2. WebWorth

    WebWorth Greenhorn

    Messages:
    89
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    20
    #2
    
    <?php
    $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
    
    function randomWord($input){
    shuffle($input);
    return $input[0];
    }
    
    echo "My matrix hero is ". randomWord($input);
    
    ?>
    PHP:
     
    Last edited: Mar 25, 2010
    WebWorth, Mar 25, 2010 IP
  3. WebWorth

    WebWorth Greenhorn

    Messages:
    89
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    20
    #3
    More specific.....

    
    <?php
    $colour = array("yellow", "green", "blue");
    $item = array("coat", "jacket", "t-shirt");
    
    function randomWord($input){
    shuffle($input);
    return $input[0];
    }
    
    echo "I wear a ". randomWord($colour) . " " . randomWord($item);
    
    ?>
    PHP:
     
    WebWorth, Mar 25, 2010 IP
  4. stOK

    stOK Active Member

    Messages:
    114
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #4
    Few months ago I did the same thing :)
     
    stOK, Mar 25, 2010 IP
  5. nickharper

    nickharper Active Member

    Messages:
    732
    Likes Received:
    16
    Best Answers:
    0
    Trophy Points:
    75
    #5
    Thanks for the reply, I can do it with that but how to I make it so I can just use the universal spinning syntax so that when something is within the tags it puts it into arrays?
     
    nickharper, Mar 26, 2010 IP
  6. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #6
    
    <?php
    
    
    $text = 'I wear a {yellow|green|blue} {coat|jacket|T shirt}.
    My mother is very {nice|mad} to me. I wish I could do things as that { but why.
    I like doing things that do not make sense}. {}';
    
    
    preg_match_all('/\{(.*[|].*)\}/Uis',$text,$result);
    
    foreach($result[1] as $curItem)
    {
    	$curArray = explode('|',$curItem);
    	$curItem = '{'.$curItem.'}';
    	$arrayCount = count($curArray);
    	$text = str_replace($curItem,$curArray[rand(0,$arrayCount-1)],$text);
    }
    
    echo $text;
    ?>
    
    PHP:
    This should do it.
     
    ThePHPMaster, Mar 26, 2010 IP