views:

561

answers:

4

This is what I have so far:

<?php
$text = preg_replace('/((\*) (.*?)\n)+/', 'awesome_code_goes_here', $text);
?>

I am successfully matching plain-text lists in the format of:

* list item 1
* list item 2

I'd like to replace it with:

<ul>
  <li>list item 1</li>
  <li>list item 2</li>
</ul>

I can't get my head around wrapping <ul> and looping through <li>s! Can anyone please help?

EDIT: Solution as answered below...

My code now reads:

$text = preg_replace('/\* (.*?)\n/', '<ul><li>$1</li></ul>', $text);
$text = preg_replace('/<\/ul><ul>/', '', $text);

That did it!

A: 

I'm not an expert with regex's, but what you're going to want to do is match the pattern you have and capture it into a backreference by surrounding the desired pattern with ()'s. You can then place $1 (for the first back reference and so on) in your "awesome code section"

Regex buddy has a really, really awesome tutorial on regular expressions if you need more

Chris Thompson
I've got $1 etc working for single matches, but I was hoping to wrap output around all matches, then add output around each match.Thanks for the link!
Al
A: 

You may use preg_match_all to match all items and then rewrite them within ul and li tags.

Ahmet Kakıcı
+2  A: 

One option would be to simply replace each list item with <ul><li>list item X</li></ul> and then run a second replace which would replace any </ul><ul> with nothing.

Amber
That did the trick, thanks! Updated question with new code
Al
A: 

I think this is what you want

<?php

$text = <<<TEXT
* item
* item
TEXT;

$html = preg_replace( "/^\\* (.*)$/m", "<li>\\1</li>", $text );

echo '<ul>', $html, '</ul>';
Peter Bailey
Thanks! But the list is buried in a huge string
Al