<?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;
Some text
<strong>Some other text</strong>
<ul>
<li>Element A1</li><li>Element A2</li>
<li>Element A3</li>
</ul>
Text that separates group A from group B
<ul>
<li>Element B1</li>
<li>Element B2</li> <li>Element B3</li>
<li>Element B4</li>
</ul>
<strong>Element that separates group B from group C</strong>
<ul>
<li>Element C1</li>
<li>Element C2</li>
</ul>
Text can follow.
<ul>
<li>Hello, nothing follows this</li>
</ul>
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
Some text
<strong>Some other text</strong>
<ul>
<li>Element A1</li><li>Element A2</li>
<li>Element A3</li>
</ul>
Text that separates group A from group B
<ul>
<li>Element B1</li>
<li>Element B2</li> <li>Element B3</li>
<li>Element B4</li>
</ul>
<strong>Element that separates group B from group C</strong>
<ul>
<li>Element C1</li>
<li>Element C2</li>
</ul>
Text can follow.
<ul>
<li>Hello, nothing follows this</li>
</ul>