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 = p开发者_JAVA百科reg_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
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>
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
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!
精彩评论