3v4l.org

run code in 300+ PHP versions simultaneously
<?php $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) { $doc = new DOMDocument; $doc->loadHTML($html); $xpath = new DOMXpath($doc); foreach ($xpath->query("//option") as $option) { $selected_value = $xpath->evaluate('string(@selected)', $option); return $selected_value; } } var_dump( get_selected($html1) ); var_dump( get_selected($html2) ); var_dump( get_selected($html3) );
Output for 5.5.24 - 5.5.35, 5.6.8 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.10, 7.2.0 - 7.2.33, 7.3.16 - 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(8) "selected" string(8) "selected" string(0) ""

preferences:
130.36 ms | 404 KiB | 176 Q