0

How can I convert a plain text list into a HTML list using regex in PHP?

Lorem ipsum.

- item 1
- item 2
- item 3
- item 4

Dolores amet.

Into

Lorem ipsum.

<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
</ul>

Dolores amet.
bart
  • 14,958
  • 21
  • 75
  • 105
  • 1
    So, as you said, using rexex, but what have you tried? – sergio Jan 17 '15 at 20:10
  • 2
    If that's a well-defined format (it looks like markdown) there's possibly a library that will do it for you. – Biffen Jan 17 '15 at 20:11
  • If you're looking for a markdown parser (which would be able to easily handle this), I would recommend [Parsedown](http://parsedown.org). – Tim Jan 17 '15 at 20:45

1 Answers1

1
  1. Regex pattern

    \n\s?-\s?(.*)
    

    example https://regex101.com/r/zQ7xL6/1

  2. Getting the matches.

    For getting every match use preg_match_all():

    preg_match_all($pattern, $your_text, $matches);

    Array (
      [0] => Array (
        [0] => 'item 1'
      )
      [1] => Array (
        [0] => 'item 2'
      )
      etc..
     )
    
  3. HTML

    Here you can do everything you want with your matches. So let's add some HTML tags.

    $html_text = '';
    foreach($matches as $match) {
      $item = $match[0]; //item 1
      $html_text .= '<li>' . $item . '</li>';
    }
    $html_text = '<ul>' . $html_text . '</ul>';
    

    Output

    <ul>
     <li>item1</li>
     <li>item2</li>
     <li>item3</li>
     <li>item4</li>
    </ul>
    
  4. preg_replace way

    For inspiration look here A regex that converts text lists to html in PHP hope I helped you.

Community
  • 1
  • 1
jmeinlschmidt
  • 1,446
  • 2
  • 14
  • 33
  • I know this is relatively old, but I believe your code should be "$matches[1] as $match" and "$item = $match". Otherwise, it doesn't execute properly. – Joe Feb 04 '22 at 07:20