PHP formatting list items

I want to convert the following text to list items

* Item 1 * Item 2 - item 1 - item 2 

to

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

I made the following regex that is not enough for this

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

but that will not work. I do not know how to do RE.

I ask myself a clearer question.

The text may or may not contain markers, and I cannot skip the loop through the file, as suggested.

Here are some examples.

 * HTML *SEO * Javascript * PHP - HTML - SEO -Javascript -PHP -HTML - SEO -Javascript -PHP 
+4
source share
3 answers

It's a little disgusting 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 * update change output

+1
source

So maybe something like:

 <?PHP $text = <<<Text * HTML *SEO * Javascript * PHP - HTML - SEO -Javascript -PHP -HTML - SEO -Javascript -PHP Text; $text = preg_replace('/(\*|-)\s*([\S]+)\s*/',"<li>$2</li>\n",$text); print $text; ?> 

which gives an output:

 <li>HTML</li> <li>SEO</li> <li>Javascript</li> <li>PHP</li> <li>HTML</li> <li>SEO</li> <li>Javascript</li> <li>PHP</li> <li>HTML</li> <li>SEO</li> <li>Javascript</li> <li>PHP</li> 
+2
source

ok, this is the best I can think of, but it solves part of the problem, maybe someone can find the best

 // first i remove the spaces after the hyphen, like in '- SEO' to have some consistency $str = str_replace ('- ','-', $str); // then i look for hyphen-word-new line and replace it with the format i want. $list = preg_replace('#\-(.*)\n#',"<li>$1</li>\n", $str); 

Obviously, this will not be entirely correct, because you still need the <ul> . so good luck!

0
source

All Articles