Miscellaneous Code
  Home arrow Miscellaneous Code arrow Amnuts MadLibs
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Download TestComplete 
JMSL Numerical Library 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MISCELLANEOUS CODE

Amnuts MadLibs
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2003-09-19

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    This class allows you to easily add a madlibs game to your website. You can load the madlib stories in via the file system or a database. The stories are chosen at random, and a form will be shown to the user to fill in their own words. You can use a few css styles to control how things look (madlibTable, madlibTitle, madlibStory, and madlibWord).

    By : amnuts

    <?php

    //
    // class.madlibs.php
    // version 1.0.0, 3rd September, 2003
    //
    // Description
    //
    // This class allows you to easily add a madlibs game to your website.
    // You can load the madlib stories in via the file system or a database.
    // If using the file system, the stories must contain the title on the
    // first line and then story in the rest of the file. If using a database
    // then the schema is as follows:
    //
    // CREATE TABLE madlibs
    // (
    // id int(11) NOT NULL auto_increment,
    // title varchar(255) NOT NULL default '',
    // story mediumtext NOT NULL,
    // PRIMARY KEY (id)
    // )
    //
    // Stories are requied to have specific tags in them for replacement. The
    // format for the tags in the stories as '{TAGNAME}'. See the function
    // 'setDefaultTags' for a list of all default tags. The class already comes
    // loaded with a vast array of tags, though you can easily add to or remove
    // from that list at run time.
    //
    // Examples of use
    //
    // Using the file system:
    //
    // require 'class.madlibs.php';
    // $ml = new madlibs();
    // $ml->useFS('./stories', '.txt');
    // $ml->displayMadlib();
    //
    // Using the file system:
    //
    // require 'class.madlibs.php';
    // $ml = new madlibs();
    // $ml->useDB('username', 'password', 'madlibs', 'mydb', 'localhost');
    // $ml->displayMadlib();
    //
    // Examples of stories
    //
    // A simple test title
    // Yesterday, {OPPOSITESEX} and I went to the beach. We had a really
    // {ADJECTIVE} time! We {VERB-ED} with my {NOUN}.
    //
    // Feedback
    //
    // There is message board at the following address:
    //
    // http://php.amnuts.com/forums/index.php
    //
    // Please use that to post up any comments, questions, bug reports, etc. You
    // can also use the board to show off your use of the script.
    //
    // Support
    //
    // If you like this script, or any of my others, then please take a moment
    // to consider giving a donation. This will encourage me to make updates and
    // create new scripts which I would make available to you. If you would like
    // to donate anything, then there is a link from my website to PayPal.
    //
    // Andrew Collington, 2003
    // php@amnuts.com, http://php.amnuts.com/
    //


    class madlibs
    {
    var $useType;
    var $dbUser;
    var $dbPass;
    var $dbHost;
    var $dbName;
    var $dbTbl;
    var $dbID;
    var $fsPath;
    var $fsExt;
    var $inText;
    var $outText;
    var $tags;
    var $tagPositions;


    //
    // the constructor
    //
    function madlibs()
    {
    $this->useType = '';
    $this->tagPositions = array();
    $this->inText = array();
    $this->outText = array();
    $this->setDefaultTags();
    }

    //
    // set the default replacement tags
    //
    function setDefaultTags()
    {
    $this->tags =
    array(
    'VERB' => 'A verb',
    'VERB-ED' => 'A verb ending in \'ed\'',
    'VERB-ING' => 'A verb ending in \'ing\'',
    'VERB-S' => 'A verb ending in \'s\'',
    'NOUN' => 'A noun',
    'NOUN-PLURAL' => 'A plural noun',
    'ADJECTIVE' => 'An adjective',
    'ADVERB' => 'An adverb',
    'EMOTION' => 'An emotion',
    'NUMBER' => 'A number',
    'PLACE' => 'The name of a place',
    'ROOM' => 'The name of a room',
    'FOOD' => 'The name of some food',
    'MALE' => 'A man\'s name',
    'FEMALE' => 'A woman\'s name',
    'OPPOSITESEX' => 'Name of a member of the opposite sex',
    'SAMESEX' => 'Name of a member of the same sex',
    'ANIMAL' => 'An animal',
    'ANIMAL-PLURAL' => 'An animal (plural)',
    'FUNNY' => 'Something funny',
    'BODYPART' => 'A body part',
    'BODYPART-PLURAL' => 'A body part (plural)',
    'CELEBRITY' => 'The name of a celebrity',
    'MADEUP' => 'Just make up a word'
    );
    }


    //
    // allows you to add new tags to the list on the fly
    // $name is the tag name, eg, 'VERB'
    // $description is the text displayed to the user, eg, 'A verb'
    //
    function addTag($name, $description)
    {
    $this->tags[$name] = $description;
    return (array_key_exists($name, $this->tags)) ? TRUE : FALSE;
    }


    //
    // allows you to remove a tag from the tag list on the fly
    // $name is the tag name, eg, 'VERB'
    //
    function deleteTag($name)
    {
    if (array_key_exists($name, $this->tags))
    {
    $this->tags[$name] = NULL;
    unset($this->tags[$name]);
    return TRUE;
    }
    else
    {
    return FALSE;
    }
    }


    //
    // sets the class to use a MySQL database for the story storage area
    // $user is the username used to access to database
    // $pass is the password for the user account
    // $table is the table name that stores the story information
    // $database is the name of the database that contains the $table
    // $host is the host address of the database
    //
    function useDB($user='username', $pass='password', $table='madlibs', $database='demo', $host='localhost')
    {
    $this->useType = 'db';
    $this->dbUser = $user;
    $this->dbPass = $pass;
    $this->dbHost = $host;
    $this->dbName = $database;
    $this->dbTbl = $table;
    $this->dbID = NULL;

    $this->dbID = @mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("Unable to connect to mysql server: {$this->dbHost}");
    @mysql_select_db($this->dbName, $this->dbID) or die("Unable to select database: {$this->dbName}");
    }


    //
    // sets the class to use the file system for the story storage area
    // $path is the path to the story files
    // $extension is the extensions of the story files, including the period if one is used
    // the name of the file is arbitrary
    //
    function useFS($path = 'stories', $extension = '.txt')
    {
    $this->useType = 'fs';
    $this->fsPath = $path;
    $this->fsExt = $extension;
    }


    //
    // loads the story information
    //
    function getStory()
    {
    if ($this->useType == 'db')
    {
    $sql = "SELECT * FROM {$this->dbTbl} " .
    ($_POST['id'] ? "WHERE id = {$_POST['id']}" : "ORDER BY RAND() LIMIT 1");
    $result = @mysql_query($sql, $this->dbID);
    if (mysql_num_rows($result))
    {
    $data = @mysql_fetch_object($result);
    $this->inText['id'] = $data->id;
    $this->inText['title'] = trim(stripslashes($data->title));
    $this->inText['story'] = trim(stripslashes($data->story));
    }
    }
    else if ($this->useType == 'fs')
    {
    if ($_POST['id'])
    {
    $file = $_POST['id'];
    }
    else
    {
    $filelist = array();
    if ($dir = @opendir($this->fsPath))
    {
    while (($file = readdir($dir)) !== FALSE)
    {
    if ($file == '.' || $file == '..') continue;
    if (preg_match("/{$this->fsExt}$/", $file))
    {
    $filelist[] = $file;
    }
    }
    closedir($dir);
    srand((float)microtime() * 10000000);
    $file = $filelist[array_rand($filelist)];
    }
    }

    $data = array();
    $data = @file($this->fsPath . '/' . $file);
    if (!empty($data))
    {
    $this->inText['id'] = $file;
    $this->inText['title'] = trim(@array_shift($data));
    $this->inText['story'] = trim(@join('', $data));
    }
    }
    }


    //
    // displays the madlib
    // if the form hasn't been displayed then it will show the form, else it
    // will show the story complete with madlib sustitutions
    //
    function displayMadlib()
    {
    $this->getStory();
    if (!isset($_POST['positions']))
    {
    if ($this->inText['story'])
    {
    $this->getTagPositions();
    $this->showForm();
    }
    else
    {
    echo 'No madlib story has been loaded.';
    }
    }
    else
    {
    if ($this->inText['story'])
    {
    $this->decompPositions($_POST['positions']);
    $this->replaceTags($_POST['word']);
    echo '<div class="madlibTitle">', $this->outText['title'], "</div>\n";
    echo '<div class="madlibStory">', nl2br($this->outText['story']), "</div>\n";
    }
    else
    {
    echo 'No madlib story has been loaded.';
    }
    }
    }


    //
    // displays the form the user's words
    //
    function showForm()
    {
    echo '<form name="madlibForm" action="', $_SERVER['PHP_SELF'], '" method="post">';
    echo '<input type="hidden" name="id" value="', urlencode($this->inText['id']), '">';
    echo '<input type="hidden" name="positions" value="', $this->compPositions(), '">';

    echo "<p>Please enter the following:</p>\n";
    echo '<table border="0" cellpadding="5" cellspacing="0" class="madlibTable">';
    foreach ($this->tagPositions as $id => $type)
    {
    echo '<tr><td>', $this->tags[$type], '</td><td><input type="textbox" name="word[', $id, ']"></td></tr>', "\n";
    }
    echo '<tr><td colspan="2" align="center"><input type="submit" value="see your madlib"></td></tr>';
    echo "\n</table>\n</form>\n";
    }


    //
    // determines where in the tags lie
    //
    function getTagPositions()
    {
    foreach ($this->tags as $key => $desc)
    {
    $positions = array();
    $tag = '{' . $key . '}';
    $positions = $this->multi_strpos($tag, $this->inText['story']);
    if (!empty($positions))
    {
    foreach ($positions as $place)
    {
    $this->tagPositions[$place] = $key;
    }
    }
    }
    ksort($this->tagPositions);
    }


    //
    // does the tag substitution for the finished story
    //
    function replaceTags($word_list)
    {
    $this->outText = $this->inText;
    if (!empty($this->tagPositions))
    {
    $tags = array_reverse($this->tagPositions, TRUE);
    foreach ($tags as $position => $type)
    {
    $tag = '{' . $type . '}';
    $this->outText['story'] = substr_replace($this->outText['story'], '<span class="madlibWord">' . $word_list[$position] . '</span>', $position, strlen($tag));
    }
    }
    }


    //
    // function to determine multiple occurrences of a word in a string
    // from a post by arduenn at hotpop dot com on the php.net comments
    //
    function multi_strpos($pattern, $sequence)
    {
    $n = -1;
    while (ereg($pattern, $sequence))
    {
    $n++;
    $fragment = split($pattern, $sequence);
    $trimsize = (strlen($fragment[0]))+1;
    $sequence = "*".substr($sequence, $trimsize);
    $position[$n] = (strlen($fragment[0]) + $position[($n-1)]);
    }
    return $position;
    }


    //
    // compresses the tag position array for use in a form
    //
    function compPositions()
    {
    return urlencode(base64_encode(serialize($this->tagPositions)));
    }


    //
    // decompresses the tag information array from a string
    // $positions is the compressed structure
    //
    function decompPositions($positions)
    {
    $this->tagPositions = unserialize(base64_decode(urldecode($positions)));
    }

    }

    ?>
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Miscellaneous Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    Build Forge Express demo: Enabling software delivery excellence for small and midsized businesses

    This demonstration gives you an overview of IBM® Rational® Build Forge Express Edition, a global offering that provides a framework to automate and execute software processes. Rational Build Forge provides a software assembly line that can support all of your tools, technologies, and platforms so you can achieve a repeatable, reliable, and traceable build and release process.
    FREE! Go There Now!


    IBM – Taking Web 2.0 to Work

    You'll get answers to many questions and more from David Barnes, Lead Evangelist for IBM Emerging Internet Technologies. David will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Evaluate Rational Host Access Transformation Services (HATS) Toolkit V7.1

    Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z

    IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects.
    FREE! Go There Now!


    NEW! IBM Rational Systems Development e-Kit

    As systems increase in complexity, communication between systems and software teams becomes more and more difficult. Now, there’s a way to improve product quality and communication.<br />Read the “Model Driven Systems Development” white paper to see how. Also included in this kit are more educational white papers, customer examples, tutorials, informative Webcasts, and best practices for designing, building and managing systems.<br />
    FREE! Go There Now!


    NEW! Run your first CICS application on a PC using TXSeries for Windows

    Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1.
    FREE! Go There Now!


    NEW! Test terminal-based applications with Rational Functional Tester

    Regression testing -- in which code is thoroughly tested to ensure that changes have not produced unexpected results -- is an important part of any development process. But many testing environments neglect the terminal-based applications that still form the backbone of many industries. In this tutorial, you'll learn how the Rational Functional Tester Extension for Terminal-Based Applications works with other Rational Functional Tester to help test terminal-based applications quickly and easily.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Functional Tester V7.0.1

    Get a free trial download of the latest version of IBM Rational Functional Tester V7.0.1. Rational Functional Tester is an automated functional and regression testing solution for QA teams concerned with the quality of their Java, Microsoft Visual Studio .NET, and Web-based applications.
    FREE! Go There Now!


    NEW! Understanding Web application security challenges

    As businesses grow increasingly dependent upon Web applications, these complex entities grow more difficult to secure. Most companies equip their Web sites with firewalls, Secure Sockets Layer (SSL), and network and host security, but the majority of attacks are on applications themselves – and these technologies cannot prevent them. This paper explains what you can do to help protect your organization, and it discusses an approach for improving your organization’s Web application security.
    FREE! Go There Now!


    NEW! Webcast: Accelerating Software Innovation with System z

    Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    MISCELLANEOUS CODE ARTICLES

    - upload image to database sql
    - Random Password Generator
    - BCroot, get the root of a number with BC fun...
    - Find pi in a high precision
    - [PHP5] FORMCHECKER : data validation
    - SPL and ITERATOR : examples
    - Xml with Rss Feeds
    - [PHP5] NOTIMEOUT PACKAGE
    - Class to return variables to a Flash movie.
    - BCGCD Greatest Common Denominator (Large Num...
    - HMAC
    - Binary to Decimal
    - Decimal to Binary using logs
    - web.framework v1.0.0
    - Shopping Cart Class





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT