Search code examples
phptext-formatting

PHP formatting list items


I want to convert following text into list items

* Item 1
* Item 2

- item 1
- item 2

to

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

I have made following regex which is not good enough for this

$text = preg_replace('#(*\s[*.]\s*)#','<li>$0</li>', $text); 

but that does not work. I am not good at making RE.

I am making question more clear here.

A text may contain bullets or may not and I cant loop through the file as atno suggested.

Here are the samples

* HTML *SEO * Javascript * PHP

- HTML
- SEO
-Javascript
-PHP

-HTML - SEO -Javascript -PHP

Solution

  • A little nasty to do with regular expressions, but here you go:

    <?php
    $text = <<<TEXT
    * HTML *SEO * Javascript * PHP
    
    - HTML
    - SEO
    -Javascript
    -PHP
    
    -HTML - SEO -Javascript -PHP
    TEXT;
    
    $text = preg_replace_callback('`([*-]\s*([^*-\r\n]+)(\r?\n)?)+`', function($m) {
        $str = '<ul>';
        $str .= preg_replace('`[*-]\s*([^*-\r\n]+)\s*`', '<li>$1</li>', $m[0]);
        $str .= '</ul>';
        return $str;
    }, $text);
    
    echo $text;
    

    I get this as output:

    *snip* clarification changes output