1

I'm creating a CMS as you might already know, and now I have a lil' problem.

Lets say: I have a textfile containing this:

[b]Some bold text[/b]
[i]Italic[/i]
- List item 1
- List item 2
- List item 3
# List item 1
# List item 2
# List item 3

And I want to convert it to:

<b>Some bold text</b>
<i>Italic</i>
<ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ul>
<ol>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ol>

The bold and italic work (with regexes), but how do I do the lists?

The '-' list should be transformed to

<ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ul>

And the '#' list to

<ol>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
</ol>

Does anybody have experience with this? Please help me. I'm using PHP 5.2.9

3 Answers 3

3

If you don't want to use an existing parsing library, you have to parse the file line by line, and to keep the current state somewhere.

If the lines starts with " - ", and the state tells you that you're not already in a list, put a <ul> plus a <li>. If you're already in a list, just put the <li>.

Same thing with lines starting with " # ".

1
  • Thanks, I dont prefer those libraries because they are about 18kb which is too big. I think I'll start list items with </li><li> to make valid XHTML.
    – user142019
    Jul 23, 2009 at 12:00
2

You might consider using another markup language such as Markdown or Textile. Then you would just have to deal with a library.

1
  • Sorry, but I don't prefer libs. They are far too big in file size. My CMS may not exceed 3000 bytes.
    – user142019
    Jul 23, 2009 at 12:01
0

OK, so you don't need all of Markdown...
but why not just take the functionality you need?

I adapted the list-processing functions to work procedurally.
To minimize file size, I compressed the verbose regexes
and removed comments related to other Markdown.
It clocks in at 3308 bytes.

Maybe it's still too bloated for your taste... d-:
but you're free to cut more corners and remove stuff.
For example, maybe you don't need nested lists.

The modified code is below.
Here's the license first:

PHP Markdown Copyright (c) 2004-2009 Michel Fortin
http://michelf.com/
All rights reserved.

Based on Markdown
Copyright (c) 2003-2006 John Gruber
http://daringfireball.net/
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 "Markdown" 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.

<?php
@define('MARKDOWN_TAB_WIDTH', 4);
$tab_width = MARKDOWN_TAB_WIDTH;
$list_level = 0;

function doLists($text) {
# Form HTML ordered (numbered) and unordered (bulleted) lists.
    global $tab_width, $list_level;
    $less_than_tab = $tab_width - 1;
    # Re-usable patterns to match list item bullets and number markers:
    $marker_ul_re  = '[*-]';
    $marker_ol_re  = '\d+[\.]';
    $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
    $markers_relist = array(
        $marker_ul_re => $marker_ol_re,
        $marker_ol_re => $marker_ul_re,
        );
    foreach ($markers_relist as $marker_re => $other_marker_re) {
        # Re-usable pattern to match any entirel ul or ol list:
        $whole_list_re = '((([ ]{0,'.$less_than_tab.'})('.$marker_re.')[ ]+)(?s:.+?)(\z|\n{2,}(?=\S)(?![ ]*'.$marker_re.'[ ]+)|(?=\n\3'.$other_marker_re.'[ ]+)))'; // mx
        # We use a different prefix before nested lists than top-level lists.
        # See extended comment in _ProcessListItems().
        if ($list_level) {
            $text = preg_replace_callback('{
                    ^
                    '.$whole_list_re.'
                }mx',
                '_doLists_callback', $text);
            }
        else {
            $text = preg_replace_callback('{
                    (?:(?<=\n)\n|\A\n?) # Must eat the newline
                    '.$whole_list_re.'
                }mx',
                '_doLists_callback', $text);
            }
        }
    return $text;
    }

function _doLists_callback($matches) {
# Re-usable patterns to match list item bullets and number markers:
    $marker_ul_re  = '[*+-]';
    $marker_ol_re  = '\d+[\.]';
    $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
    $list = $matches[1];
    $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
    $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
    $list .= "\n";
    $result = processListItems($list, $marker_any_re);
    $result = "<$list_type>\n" . $result . "</$list_type>";
    return "\n". $result ."\n\n";
    }

function processListItems($list_str, $marker_any_re) {
#   Process the contents of a single ordered or unordered list, splitting it
#   into individual list items.
# The $list_level global keeps track of when we're inside a list.
# Each time we enter a list, we increment it; when we leave a list,
# we decrement. If it's zero, we're not in a list anymore.
    global $list_level;
    $list_level++;
# trim trailing blank lines:
    $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
    $list_str = preg_replace_callback('{(\n)?(^[ ]*)('.$marker_any_re.'(?:[ ]+|(?=\n)))((?s:.*?))(?:(\n+(?=\n))|\n)(?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))}xm','_processListItems_callback', $list_str);
    $list_level--;
    return $list_str;
    }

function _processListItems_callback($matches) {
    $item = $matches[4];
    $leading_line =& $matches[1];
    $leading_space =& $matches[2];
    $marker_space = $matches[3];
    $tailing_blank_line =& $matches[5];
    if ($leading_line || $tailing_blank_line
    || preg_match('/\n{2,}/', $item))
        { # Replace marker with the appropriate whitespace indentation
        $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
        $item = outdent($item)."\n";
        }
    else { # Recursion for sub-lists:
        $item = doLists(outdent($item));
        $item = preg_replace('/\n+$/', '', $item);
        }
    return "<li>" . $item . "</li>\n";
    }

function outdent($text) {
# Remove one level of line-leading tabs or spaces
    global $tab_width;
    return preg_replace('/^(\t|[ ]{1,'.$tab_width.'})/m', '', $text);
    }
?>
1
  • By the way -- a CMS in PHP with a constraint of 3000 bytes?! Yowza, that'd be impressive. So have you finished and are you sharing? I'd be particularly interested in a lighter-weight list-parsing function, if you wrote a good one based on FWH's suggestion. Cheers. Aug 29, 2012 at 0:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.