Catgut

catgut.php

<?php

/*
Catgut knows xhtml so you don't have to. Relax. Take a rest.
Nick B-W <nick@panharmonicon.com>

Catgut takes a string containing simple, intuitive markdown, and converts it
to strict xhtml. It provides only the parsing engine -- storage, retrieval, and
integrity checking of user-submitted text is up to the containing script.

The markdown is easily extended, and can be modified on a per-object basis  --
examine the ->filters array of the catgut object class. This also includes
built-in documentation of the default markdown tags.

Copyright (c) 2005, Nick Blanchard-Wright
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Panharmonicon nor the names of its contributors may 
  be used to endorse or promote products derived from this software without 
  specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

class catgut {
    function 
catgut($string$headerlevel=0) {
        
$this->string $string// Hurray!
        
$this->headerlevel $headerlevel;
        
$this->filters = array( // Have some defaults.
            // Get it? They're regular expressions!
            
'contractions' => array(
                
're' => "/(\D)'(\w{1,2})\b/",
                
'replace' => '$1&#x2019;$2',
                
'description' => "foo'd becomes foo&#x2019;d"
            
),
            
'possessive' => array(
                
're' => "/s'\B/",
                
'replace' => 's&#x2019;',
                
'description' => "foos' bar becomes foos&#x2019; bar"
            
),
            
'doublequotes' => array(
                
're' => '/\B"(\w(\d"|.)*)"\B/U',
                
'replace' => '&#8220;$1&#8221;',
                
'description' => '"foo" becomes &#8220;foo&#8221;'
            
),
            
'singlequotes' => array(
                
're' => "/\B'(\w(\d'|.)*)'\B/U",
                
'replace' => '&#x2018;$1&#x2019;',
                
'description' => "'foo' becomes &#x2018;foo&#x2019;"
            
),
            
'ellipses' => array(
                
're' => '/\.{3}/',
                
'replace' => '&#x2026;',
                
'description' => 'foo ... bar becomes foo &#x2026; bar'
            
),
            
'endash' => array(
                
're' => '/(\s)--(\s)/',
                
'replace' => '$1&ndash;$2',
                
'description' => 'foo -- bar becomes foo &ndash; bar'
            
),
            
'emdash' => array(
                
're' => '/(\w)--(\w)/',
                
'replace' => '$1&mdash;$2',
                
'description' => 'foo--bar becomes foo&mdash;bar'
            
),
            
'newline' => array(
                
're' => '/(.)\n(.)/',
                
'replace' => "$1\n<br />\n$2",
                
'description' => 'foo\nbar becomes foo\n<br />\nbar'
            
),
            
'strong' => array(
                
're' => '/(\B)-(.*[^-].*)-(\B)/U'
                
'open' => '<strong>'
                
'close' => '</strong>',
                
'description' => '-foo- becomes <strong>foo</strong>'
            
),
            
'em' => array(
                
're' => '/(^|[^:\/]\B)\/(.+)\/(\B)/U'
                
'open' => '<em>'
                
'close' => '</em>',
                
'description' => '/foo/ becomes <em>foo</em>'
            
),
            
'cite' => array(
                
're' => '/(\W)_(.+)_(\W)/U'
                
'open' => '<cite>'
                
'close' => '</cite>',
                
'description' => '_foo_ becomes <cite>foo</cite>'
            
),
            
'paragraph' => array(
                
're' => '/(^|\n{2,})(.*\S.*)(?=\n{2,}|$)/Us'
                
'open' => '<p>'
                
'close' => '</p>',
                
'description' => 'foo\n\n becomes <p>foo</p>'
            
),
            
'blockquote' => array(
                
're' => '/&openparagraph;(\t+)(.+)&closeparagraph;/Us'
                
'open' => '<blockquote>',
                
'close' => '</blockquote>',
                
'description' => '\tfoo becomes <blockquote>foo</blockquote>'
            
),
            
'header' => array(
                
're' => '/&openparagraph;(!+?)(.+)&closeparagraph;/Us',
                
'open' =>'<h1>',
                
'close' => '</h1>',
                
'callback' => 'header',
                
'description' => '!foo becomes <h1>foo</h1>'
            
),
            
'horizontalrule' => array(
                
're' => '/&openparagraph;-{4,}&closeparagraph;/Us',
                
'replace' => '<hr />',
                
'description' => '--------- becomes <hr />'
            
),
            
'link' => array(
                
're' => '/\[(.+)\]/U',
                
'callback' => 'link',
                
'description' => '[foo|bar] becomes <a href="foo">bar</a>'
            
)
        );
    }

    function 
transform() {
        
// The basics.
        
$string str_replace("\r\n""\n"$this->string); // Lousy Windows
        
$string str_replace("\r""\n"$string); // Lousy Apple
        
$string preg_replace("/ {4,}/""\t"$string); // I like tabs.
        
$string preg_replace('/^\s+$/m'""$string); // Empty lines should be empty
        
$string htmlentities($stringENT_NOQUOTES); // Mmm.
        // The fun part.
        
foreach($this->filters as $name=>$filter) {
            if(isset(
$filter['callback'])) {
                
$string preg_replace_callback($filter['re'], array($this$filter['callback']), $string);
            } elseif(isset(
$filter['replace'])) {
                
$string preg_replace($filter['re'], $filter['replace'], $string);
            } elseif(isset(
$filter['open']) and isset($filter['close'])) {
                
$string preg_replace($filter['re'], "$1&open$name;$2&close$name;$3"$string);
            }
        }
        
// Clean up for open/close style filters.
        
$string preg_replace_callback('/&(open|close)(.+);/U', array($this'replace'), $string);
        return(
$string);
    }

    
// Track header levels
    
function header($string) {    
        
$headn strlen($string[1]);
        if(isset(
$this->headerlevel) and is_int($this->headerlevel)) { $headn $headn abs($this->headerlevel); }
        if(
$headn 6) { $headn 6; }
        
$open str_replace('<h1'"<h$headn"$this->filters['header']['open']);
        
$close  str_replace('h1>'"h$headn>"$this->filters['header']['close']);
        return(
$open $string[2] . $close);
    }

    
// Bracket links are easy on the n00bs.
    
function link($string) {
        
$link explode("|"$string[1]);    
        if(
count($link) > 1) {
            
$text array_pop($link);
        }
        
$link implode("|"$link);
        
$return "<a href=\"";
        if(
preg_match("/^[^:]+@[^:]+$/"$link)) {
            
$return $return "mailto:";
            
$return $return $link "\">";
        } else {
            
$return $return $link "\">";
        }
        if(!
$text) {
            
$text $link;
        }
        
$return $return $text "</a>";
        return(
$return);
    }


    
// The $open array enforces nesting.
    
function replace($string) {
        static 
$open = array();
        if(
$string[1] == 'open') {
            
array_unshift($open$string[2]);
            return(
$this->filters[$string[2]]['open']);
        } elseif(
$string[1] == 'close') {
            if(
count($open)) {
                
$return '';
                
$nested = array();
                while(
$open[0] != $string[2]) {
                    
$now array_shift($open);
                    
$nested[] = $now;
                    
$return .= $this->filters[$now]['close'];
                }
                
array_shift($open);
                
$return .= $this->filters[$string[2]]['close'];
                foreach(
$nested as $nest) {
                    
$return .= $this->filters[$nest]['open'];
                    
array_unshift($open$nest);
                }
                return(
$return);
            }
        }
        return(
'');
    }
}
?>