3v4l.org

run code in 300+ PHP versions simultaneously
<?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;
Output for 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
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>

preferences:
105.92 ms | 2078 KiB | 4 Q