Mamadou Mamadou - 8 months ago 32
PHP Question

How to split an HTML string into chunks in PHP?

I would like to split a string efficiently into different sub strings like this :


I would like to split this string in 3 parts and put each string in a variable.

The first variable $first should contain the first li (
The second variable $second should contain the rest expect the last (
The third variable $third should contain the last li (

Anyone can help ?


The best thing to do here, because you're dealing with markup, is to treat the data as what it is: HTML. Parse the DOM tree, iterate over the nodes you're interested in and get the data like so:

$dom = new DOMDocument;
$dom->loadHTML($data);//parses the markup string
$li = $dom->getElementsByTagName('li');
$liValues = [];
foreach ($li as $elem) {
    $liValues[] = $elem->nodeValue;

To get the first, last and middle elements, just write this:

$length = count($li);//get the total number of li's
$nodes = [
    $li->item(0), //first
    $li->item(round($length/2)), // middle
    $li->item($length -1), // last

Or just get the parent node (ul or ol), and use $parent->firstChild and $parent->lastChild to get the first and last elements in the list, as CD001 suggested in the comments.

Useful links:

You can use the attributes property of the DOMNode elements in the DOMNodeList returned by getElementsByTagName to further exapand on the data you store