Markdown lite. Codice gratis e (forse) utile
  • In diretta da GamesVillage.it
    • News
    • -
    • In Evidenza
    • -
    • Recensioni
    • -
    • RetroGaming
    • -
    • Anteprime
    • -
    • Video
    • -
    • Cinema

Visualizzazione risultati da 1 a 6 di 6

Discussione: Markdown lite. Codice gratis e (forse) utile

Cambio titolo
  1. #1
    (un po' meno) cattivo L'avatar di L33T
    Registrato il
    10-02
    Località
    Ovunque e in nessun luogo
    Messaggi
    3.908

    Markdown lite. Codice gratis e (forse) utile

    Markdown è un formato splendido, ma fin troppo potente. La possibilità di inserire html inline, la possibilità di inserire tutti e 6 i livelli di header, la possibilità di inserire liste nidificate sono feature che al 90% sono solo d'impiccio.
    Visto che non è semplice modificare il parser originale ne ho riscritto uno che implementi solo le feature che mi interessano (vedi). Non so quanto possa esservi utile, io comunque lo condivido. Ovviamente suggerimenti & critiche sono ben accetti.

    Codice PHP:
    <?php
    /**
     * A parser for a subset of Markdown
     */
    class Markdown{
        
    /**
         * @var string The text to convert
         */
        
    private $text null;
        
    /**
         * @var mixed The text's blocks
         */
        
    private $blocks null;
        
    /**
         * Instances the class and loads the text
         */
        
    public function __construct($text null){
                if (!empty(
    $text)){        
                
    $this->text $text;
            }
        }
        
    /**
         * Converts the plain text in html
         * @return string The converted text
         */
        
    public function convert($text null){
            if (!empty(
    $text)){
                
    $this->text $text;
            }
            
    $this->prepare();
            
    $this->block();
            
    $this->inline();
            
    $this->finalize();
            return 
    $this->text;
        }
        
    /**
         * Cleans up the text. Normalizes new lines, replace new lines with §, encode some chars etc..
         */
        
    private function prepare(){
            
    $this->text trim(str_replace(array("\r\n""\r""\n"), "§"$this->text));
            
    $patterns = array(
                
    '/[§]{2,}/is' // max two new lines
            
    );
            
    $replacements = array(
                
    "§§"
            
    );
            
    $this->text preg_replace($patterns,$replacements,$this->text);
            
    $this->encode();
        }
        
    /**
         * Replaces some chars with their entities
         */
        
    private function encode(){
            
    $patterns = array(
                
    '/[&](?![#a-zA-Z0-9]*;)/i'// replaces & with &amp; unless it's used in a entity
                
    '/(?<!§|^|\\\)[>](?=[^ ]?)/i'// replaces > with &gt; unless it's used to start a blockquote
                
    '/[<]/i' // replaces < with &lt;
            
    );
            
    $replacements = array(
                
    "&amp;",
                
    "&gt;",
                
    "&lt;"
            
    );
            
    $this->text preg_replace($patterns,$replacements,$this->text);
        }
        
    /**
         * Wraps block elements in the appropriate tags
         */
        
    private function block(){
            
    $this->splitBlocks();
            foreach(
    $this->blocks as &$block){
                
    $chars substr($block,0,2);
                switch (
    $chars){
                    
    // blockquote
                    
    case '> ':
                        
    $this->doBlockquote($block);
                    break;
                    
    // list
                    
    case '+ ':
                        
    $this->doList($block);
                    break;
                    
    // header or paragraph
                    
    default:
                        if (!
    strstr($block,'§===')){
                            
    $this->doParagraph($block);
                        }
                        else{
                            
    $this->doHeader($block);
                        }
                    break;
                }
            }
            
    $this->finalizeBlocks();
        }
        
    /**
         * Utility: splits the text's blocks in an array
         */
        
    private function splitBlocks(){
            
    $this->blocks explode("§§",$this->text);
        }
        
    /**
         * Marks the block as a blockquote
         */
        
    private function doBlockquote(&$block){
            
    $lines explode('§',$block);
            foreach (
    $lines as &$line){
                
    $line substr($line,2,strlen($line)-2);
            }
            
    $block "<blockquote>§\t<p>".implode('',$lines).'</p>§</blockquote>';
        }
        
    /**
         * Marks the block as a list
         */
        
    private function doList(&$block){
            
    $lines explode('§',$block);
            foreach (
    $lines as &$line){
                
    $line "\t<li>".substr($line,2,strlen($line)-2).'</li>§';
            }
            
    $block '<ul>§'.implode('',$lines).'</ul>';
        }
        
    /**
         * Marks the block as a paragraph
         */
        
    private function doParagraph(&$block){
            if (
    strlen($block) > 0){
                
    $block '<p>'.str_replace('§','',$block).'</p>';
            }
        }
        
    /**
         * Marks the block as a header
         */
        
    private function doHeader(&$block){
            
    $lines explode('§',$block);
            
    $block '<h3>'.$lines[0].'</h3>';
        }
        
    /**
         * Evaluates the inline elements: bold text, italic text, links
         */
        
    private function inline(){
            
    $patterns = array(
                
    '/(?<![\\\])\[(.*)\]\((.*)\)/i'// links
                
    '/__(.*?)__/i'// bold (will the lazy evaluation mess up all?..)
                
    '/(?<![\\\])_(.*?)_/i' // italic (same thing as bold)
            
    );
            
    $replacements = array(
                
    "<a href=\"$2\">$1</a>",
                
    "<strong>$1</strong>",
                
    "<em>$1</em>"
            
    );
            
    $this->text preg_replace($patterns,$replacements,$this->text);
        }
        
    /**
         * Utility: rejoins the block elements etc..
         */
        
    private function finalizeBlocks(){
            
    $this->text implode("\n\n",$this->blocks);
        }
        
    /**
         * Replaces § with new lines and handles escaped chars
         */
        
    private function finalize(){
            
    $replace = array(
                
    '§'=>"\n",
                
    '\>'=>'>',
                
    '\+'=>'+',
                
    '\`'=>'`',
                
    '\*'=>'*',
                
    '\_'=>'_',
                
    '\{'=>'{',
                
    '\}'=>'}',
                
    '\['=>'[',
                
    '\]'=>']',
                
    '\('=>'(',
                
    '\)'=>')',
                
    '\#'=>'#',
                
    '\-'=>'-',
                
    '\.'=>'.',
                
    '\!'=>'!'
            
    );
            
    $this->text str_replace(array_keys($replace),array_values($replace),$this->text);
        }
    }
    ?>
    Ultima modifica di L33T; 10-03-2007 alle 22:31:27
    Es ist nichts schrecklicher als eine tätige Unwissenheit.

  2. #2
    Puppppppaaaaaaaaaaa L'avatar di Revan1985
    Registrato il
    01-06
    Località
    Solbiate Olona
    Messaggi
    1.655
    credo che possa essere utile ai web-bisti...

    io non lo guarderò nemmeno, non per mancanza di rispetto, am perchè il linguaggio per il web francamente non mi interessa
    È stato detto che la democrazia è la peggior forma di governo, eccezion fatta per tutte quelle altre forme che si sono sperimentate finora.


  3. #3
    Bannato L'avatar di The Lord of Diplomacy
    Registrato il
    08-06
    Località
    Helos
    Messaggi
    3.107
    Grazie L33T, pu&#242; tornarmi utile, appena ho tempo gli d&#242; un occhiata approfondita.

  4. #4
    ~ Over My Head ~ L'avatar di Finalfire
    Registrato il
    06-03
    Località
    Italy
    Messaggi
    5.011
    Good job. Se riesco, a breve una implementazione in JSP.

  5. #5
    Headless Dove L'avatar di sydarex
    Registrato il
    07-04
    Messaggi
    7.847
    Bravo L33T.
    Quali features implementa (sono troppo pigro per leggere il tuo codice) ?


  6. #6
    (un po' meno) cattivo L'avatar di L33T
    Registrato il
    10-02
    Località
    Ovunque e in nessun luogo
    Messaggi
    3.908
    Paragrafi, liste e blockquote non nested, header non atx, grassetto, corsivo, link.
    Per capirci, trasforma

    Codice:
    lorem ipsum
    ================
    
    lorem __ipsum__ dolor _sit_ amet 
    lorem ipsum dolor [sit](http://www.url.it) amet
    
    + lorem
    + ipsum
    
    > lorem ipsum 
    > dolor sit amet
    in

    Codice:
    <h3>lorem ipsum</h3>
    <p>lorem <strong>ipsum</strong> dolor <em>sit</em> amet lorem ipsum dolor <a href="http://www.url.it">sit</a> amet</p>
    <ul>
    <li>lorem</li>
    <li>ipsum</li>
    </ul>
    <blockquote>
    <p>lorem ipsum dolor sit amet</p>
    </blockquote>
    Es ist nichts schrecklicher als eine tätige Unwissenheit.

Regole di Scrittura

  • Tu non puoi inviare nuove discussioni
  • Tu non puoi inviare risposte
  • Tu non puoi inviare allegati
  • Tu non puoi modificare i tuoi messaggi
  •