I have following code:
<?php
$html = '<div>
<div class="block">
<div class="id">10</div>
<div class="name">first element</div>
</div>
<div class="block">
<div class="name">second element</div>
</div>
<div class="block">
<div class="id">30</div>
<div class="name">third element</div>
</div>
</div>';
preg_match_all('/<div class="block">[\s]+<div class="id">(.*?)<\/div>[\s]+<div class="name">(.*?)<\/div>[\s]+<\/div>/ms', $html, $matches);
print_r($matches);
I want to get array with id and name, but the second position doesn't have id, so my preg match skipped this one. How can I generate array without skip and print sth like this [ ... [id => 0 // or null, name => 'second element'] ...]?
Use
DOMDocumentto solve this task; there are a lot of good reasons not to use regular expressions.Assuming your HTML code is stored in
$htmlvariable, create an instance ofDOMDocument, load the HTML code, and initializeDOMXPath:Use
DOMXPathto search for all<div>nodes with class "name" and prepare an empty array for the results:For each node found, run an additional query to find the optional node with class "id", then add a record to the results array:
This is the result: