Selecting and checking items from HTML menus
This is handy for making persistent forms without polluting the HTML with PHP logic. For example, you could initialize all your menus to have nothing selected and then pass in GET or POST variables in case the form was not accepted, easily making form selections persistent.
/** * For select menus. */ function select_from_menu($menu,$choices,$deselect=true) { if ($deselect) $menu = preg_replace('/ selected(="selected")?/','',$menu); if(!is_array($choices)) { $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 selected=\"selected\"",$menu); } else foreach($choices as $value) { $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 selected=\"selected\"",$menu); } return $menu; } /** * For radio buttons and checkboxes. */ function check_from_menu($menu,$choices,$deselect=true) { if ($deselect) $menu = preg_replace('/ checked(="checked")?/','',$menu); if(!is_array($choices)) { $menu = preg_replace('/(value="'.preg_quote($choices).'")/',"$1 checked=\"checked\"",$menu); } else foreach($choices as $value) { $menu = preg_replace('/(value="'.preg_quote($value).'")/',"$1 checked=\"checked\"",$menu); } return $menu; }