May 272011
 

I was bored the other day so I made a very simple article spinner…

Takes a sentence like this:
The {quick|fast} {brown|black} {fox|dog|cat} jumps {over|above|around} the {lazy|sleepy} {horse|cow|donkey}.

And turns it into something like:
The fast brown cat jumps above the sleepy donkey.

$content = "The {quick|fast} {brown|black} {fox|dog|cat} jumps 
{over|above|around} the {lazy|sleepy} {horse|cow|donkey}.";
function spinaround($content)
{
    preg_match_all('/{(.*)}/sU',$content,$matches);
    foreach ($matches[0] as $k=>$v)
    {
        $string = $matches[1][$k];
        $new = explode('|',$string);
        $new = $new[array_rand($new)];
        $content = str_replace($v,$new,$content);
    }
return $content;
}
echo spinaround($content);

I know what you’re thinking; “But most article spinners can do two levels of spinning!!” Yeah, well, using regex to do so is a bit of a pain, however using square brackets [ ] this is entirely possible, as follows:

Takes this:
The {quick|fast} {brown|black} {fox|[fat|skinny] dog|cat} jumps {over|above [and beyond|and below]|around} the {[overly|somewhat] lazy|sleepy}
{horse|cow|donkey}.

Turns it into:
The fast brown fox jumps above and beyond the overly lazy horse.

$content = "The {quick|fast} {brown|black} {fox|[fat|skinny] dog|cat} jumps 
{over|above [and beyond|and below]|around} the {[overly|somewhat] lazy|sleepy}
{horse|cow|donkey}.";
function spinaround($content)
{
    preg_match_all('/{(.*)}/sU',$content,$matches);
    foreach ($matches[0] as $k=>$v)
    {
        $string = $matches[1][$k];
        if ( preg_match_all('/\[(.*)\]/sU',$string,$stringmatches) )
        {
            foreach ($stringmatches[0] as $l=>$w)
            {
            $new = explode('|',$stringmatches[1][$l]);
            $new = $new[array_rand($new)];
            $string = str_replace($w,$new,$string);
            }
        }
        $new = explode('|',$string);
        $new = $new[array_rand($new)];
        $content = str_replace($v,$new,$content);
    }
return $content;
}
 
echo spinaround($content);

Now I know the standard ‘spinables’ use { } for both sets of spinning, but oh well.

Enjoy.

  2 Responses to “PHP Snippet – Article Spinner”

Comments (2)
  1. Thanks. That is very interesting.

  2. thanks

Sorry, the comment form is closed at this time.