Maximus
Maximus

Reputation: 2976

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

Upvotes: 4

Views: 661

Answers (3)

mpen
mpen

Reputation: 282815

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

Upvotes: 1

Ibu
Ibu

Reputation: 43810

ok this is the best i can come up with but it solve part of the problem, maybe someone else can find a better

// 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 completely correct because you still need the <ul> tag. so good luck!

Upvotes: 0

Pollett
Pollett

Reputation: 596

So maybe something along the lines of:

<?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 of:

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

Upvotes: 2

Related Questions