2

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!

1
  • You may use preg_match_all to match all items and then rewrite them within ul and li tags. Commented Aug 9, 2009 at 22:32

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

0

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

1 Comment

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!
0

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>';

1 Comment

Thanks! But the list is buried in a huge string

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.