A 5 line quote script in PHP

…mainly because Ben has taken too long to write his own (I don’t think he was try­ing, but meh… no more excuses!)

18 lines of com­ments, and 5 lines of code. If this is too hard to use, you shouldn’t be using PHP (or any pro­gram­ming lan­guage, for that matter!)

<?php
#-----Simple Random Quote script-------#
# Place this file somewhere servable,  #
# and stick a file "quotes.txt" in the #
# same directory as it. Alternatively, #
# change the $quotesfile variable to   #
# something desirable.                 #
#                                      #
# IMPORTANT: Quotes file must be       #
# server readable. Obvious, but often  #
# overlooked.                          #
#                                      #
# quotes.txt format is:                #
# Quotation::Author                    #
# Use one entry per line only.         #
#                                      #
# Output from the regex replacement is:#
# <p>Quotation<br /><em>Author</em></p>#
#--------------------------------------#

$quotefile = "quotes.txt";
if ($quotes = file($quotefile)) {
 echo eregi_replace("([^[]*)::([^[]*)","<p>1<br /><em>2</em></p>", $quotes[array_rand($quotes)]);
} else{
 echo 'An error has occurred, no quotes are available at this time.';
} ?>

I hope Word­Press doesn’t mess that up…

Tags: , , , ,

posted on Saturday, March 26th, 2005 at 11:06 pm by Josh Street, filed under Geek, PHP, Quotations.

6 Responses to “A 5 line quote script in PHP”

  1. dale says:

    You have an error in your regex, should read:

    echo eregi_replace("([^[]*)::([^[]*)","

    \1
    \2

    ", $quotes[array_rand($quotes)]);

  2. cat-man says:

    *rolls eyes* 8-)

    thanks joshua

  3. dale says:

    Oh I’m going to piss you off but what­ever :p

    Regex is known to be pretty slow. Why not use the built in func­tion explode? Then you don’t need to try and get your head around what that pat­tern does! :p


    $quotes = explode('::', $quotes[array_rand($quotes)]);
    echo '

    '.$quotes[0].'
    '. $quotes[1] .'

    ';

  4. Josh says:

    I thought it needed the slashes, too, but then it wasn’t work­ing with them so I got rid of them and it was fine… shrug!

    p.s. if you’re using tags in your <code>, you still need to use entity codes — e.g.  gt; and lt;

  5. Josh says:

    Oh, and hav­ing viewed the raw com­ments Dale entered, here’s his patch done prop­erly (e.g. pre­serv­ing the HTML tags)


    $quotes = explode('::', $quotes[array_rand($quotes)]);
    echo '<p>'.$quotes[0].'<br /><em>'. $quotes[1] .'</em></p>';

  6. dale says:

    Ah thanks for that. Crazy html, scary stuff. ;)

Leave a Reply