Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

I know that this is an old post - but it needs a solution. Try this! :)

$text = preg_replace("/\[ul\](.*)\[\/ul\]/Usi", "<ul>\\1</ul>", $text);
$text = preg_replace("/\[li\](.*)\[\/li\]/Usi", "<li>\\1</li>", $text);

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

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

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>';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top