- strstr: documentation ( source)
- explode: documentation ( source)
<?php
function isLi($line) {
return strstr($line, '<li');
}
$text = 'Some text
<strong>Some other text</strong>
<li>Element A1</li><li>Element A2</li>
<li>Element A3</li>
Text that separates group A from group B
<li>Element B1</li>
<li>Element B2</li> <li>Element B3</li>
<li>Element B4</li>
<strong>Element that separates group B from group C</strong>
<li>Element C1</li>
<li>Element C2</li>
Text can follow.
<li>Hello, nothing follows this</li>';
$array = explode("\n", $text);
$html = '';
$previousWasLi = false;
foreach ($array as $line) {
if (empty($line)) {
continue;
}
if (isLi($line) && $previousWasLi == false) {
$html .= "<ul>\n";
$html .= $line ."\n";
$previousWasLi = true;
} elseif (isLi($line) && $previousWasLi == true) {
$html .= $line ."\n";
$previousWasLi = true;
} elseif (!isLi($line) && $previousWasLi == true) {
$html .= "</ul>\n";
$html .= $line ."\n";
$previousWasLi = false;
} elseif (!isLi($line) && $previousWasLi == false) {
$html .= $line ."\n";
}
}
// if the last line was an li, we need to close the ul
if ($previousWasLi) {
$html .= '</ul>';
}
echo $html;