jjones150
jjones150

Reputation: 302

Sorting Arrays in Order they are Found in a Document - preg_match_all

I am attempting to use preg_match_all in my php script to capture corresponding values into two separate arrays.

ex.

<p>
   <span id="calibration_test_name_0">blah blah blah</span>
   <span id="calibration_test_instrument_0">blah blah blah</span>
</p>
<p>
   <span id="calibration_test_name_1">blah blah blah</span>
   <span id="calibration_test_instrument_1">blah blah blah</span>
</p>

I am creating two separate arrays (one for the test name, one for the test instrument). I want to output test_name_0 with test_instrument_0. And so on, but I am getting results that are out of order. I know this has to do with the sort. Is there anyway to sort these two arrays in the order that they appear in the document? Any help is appreciated.

Upvotes: 0

Views: 42

Answers (2)

Jan
Jan

Reputation: 43169

The answer: use a Parser instead. If you have as many names as instruments, you could come up with the following approach.

Code:

<?php

// your html
$html = <<<EOF
<p>
   <span id="calibration_test_name_0">blah blah blah</span>
   <span id="calibration_test_instrument_0">blah blah blah</span>
</p>
<p>
   <span id="calibration_test_name_1">blah blah blah</span>
   <span id="calibration_test_instrument_1">blah blah blah</span>
</p>
EOF;

// load the DOM
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);

$prefix = 'calibration_test_';
$xnames = $prefix . "name";
$xinstruments = $prefix . "instrument";

$names = iterator_to_array($xpath->query("//span[starts-with(@id, '$xnames')]"));
$instruments = iterator_to_array($xpath->query("//span[starts-with(@id, '$xinstruments')]"));

// loop over the found items
for ($i=0;$i<count($names);$i++)
    echo "Name: " . $names[$i]->nodeValue . ", Instrument: " . $instruments[$i]->nodeValue . "\n";
?>

Explanation:

The snippet loads your html string into a DOM and runs two xpath queries against it. These are converted to arrays and looped over afterwards.

Demo:

See a working demo on ideone.com.

Upvotes: 2

JesusTheHun
JesusTheHun

Reputation: 1237

If your input is valid xml, then you should using an XML parser and not a REGEXP. The order has a lot to do with REGEXP actually, if you use named pattern you should be able to retrieve your content in the correct order. Again, XML parser is better if your input is XML valid.

Upvotes: 1

Related Questions