<?php
// http://stackoverflow.com/questions/34416490/how-to-match-html-selected-option-with-preg-match
$html1 = <<<EOT
<option selected="selected" value="1">value text</option>
EOT;
$html2 = <<<EOT
<option selected value="1">value text</option>
EOT;
$html3 = <<<EOT
<option value="the devil with **selected** ">value text</option>
EOT;
$html4 = <<<EOT
<option selected="selected" value="1">value text</option>
<option value="the devil with **selected** ">value text</option>
<option selected value="1">value text</option>
EOT;
function get_selected($html) {
$results = array();
$doc = new DOMDocument;
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
foreach ($xpath->query("//option") as $option) {
$selected_value = $xpath->evaluate('string(@selected)', $option);
$results[] = $selected_value;
}
return $results;
}
var_dump( '1', get_selected($html1) );
var_dump( '2', get_selected($html2) );
var_dump( '3', get_selected($html3) );
var_dump( '4', get_selected($html4) );
- Output for 5.5.0 - 5.5.38, 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.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
- string(1) "1"
array(1) {
[0]=>
string(8) "selected"
}
string(1) "2"
array(1) {
[0]=>
string(8) "selected"
}
string(1) "3"
array(1) {
[0]=>
string(0) ""
}
string(1) "4"
array(3) {
[0]=>
string(8) "selected"
[1]=>
string(0) ""
[2]=>
string(8) "selected"
}
preferences:
201.14 ms | 404 KiB | 326 Q