tags:

views:

88

answers:

3

Hi,

I'm trying to code a regexp to convert a block of text:

* List item
* Another list item

to html:

<ul>
    <li>List item</li>
    <li>Another list item</li>
</ul>

I know there are snippets or classes to do this (Markdown, Textile, etc) but I think it's overkill: I really just want some basic functionality. So far I'm trying with:

$text = preg_replace("/\*+(.*)?/i","<li>$1</li>",$text);

But I don't know how to wrap everything in <ul> tags without using a separate replace, like so:

$text = preg_replace("/(\<li\>(.*)\<\/li\>\n*)+/is","<ul>\n$1\n</ul>\n",$text);

This interferes with other code, for example ordered lists. There must be a better way.

Thanks.

A: 

Well, you could simply do

$text = "<ul>" . preg_replace("/\*+(.*)?/i","<li>$1</li>",$text) . "</ul>";

or, if you really want to use preg_replace

$text = preg_replace("/(\<li\>(.*?)\<\/li\>\n*)+/is","<ul>\n$1\n</ul>\n",$text);
Paulo Santos
Again, maybe I didn't make this clear (sorry), but there are more things in $text, so adding <ul> won't work.
Reven
+1  A: 

Why don't you store the first regex in an array with preg_match_all, and glue it like this:

$list='<ul><li>';
$list .= implode('</li><li>',$arr_regex);
$list .= '</li></ul>';
DCC
That would work if the text was the only element in the block of text, but there are things before and after.
Reven
A: 

Perhaps you may find PHP Markdown useful.

Ignacio Vazquez-Abrams
Was kind of trying to avoid using it, to be honest. Just need a couple of substitutions. My script is about 10Kb. Including a 40Kb script just to do that seems overkill.
Reven