Monday, February 21, 2011

PHP automatic list creation from a textfile to (X)HTML

Hi all people!

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

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

    Time Machine : Sorry, but I don't prefer libs. They are far too big in file size. My CMS may not exceed 3000 bytes.
  • 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 " # ".

    Time Machine : Thanks, I dont prefer those libraries because they are about 18kb which is too big. I think I'll start list items with
  • to make valid XHTML.

0 comments:

Post a Comment