This question already has an answer here:
I would like to split a string efficiently into different sub strings like this :
<li><a href="">One</a></li><li><a href>Two</a></li><li><a href>Three</a></li>.....<li><a herf>Last</a></li>
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 (<li>One</li>
)
The second variable $second should contain the rest expect the last (<li>Two</li><li>Three</li>.....
)
The third variable $third should contain the last li (<li>Last</li>
)
Anyone can help ?
you can try with explode
see code example:
Should work:
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:
To get the first, last and middle elements, just write this:
Or just get the parent node (
ul
orol
), 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 theDOMNode
elements in theDOMNodeList
returned bygetElementsByTagName
to further exapand on the data you store