Hady Shaltout
Hady Shaltout

Reputation: 634

convert html select to an array php

The html select code generated by using (wp_dropdown_categories) WordPress function and i want to convert it into an array urgently.

<select name="selectname1" id="selectId1" class="postform">
<option value="0">Recent Posts</option>
<option class="level-0" value="1">Uncategorized</option>
<option class="level-0" value="2">World News</option>
<option class="level-1" value="3">&nbsp;&nbsp;&nbsp;Political</option>

So i need to be something like that (Key, Value)

Array('Recent Posts' => '0',
'Uncategorized' = > '1',
'World News' = > '2',
'&nbsp;&nbsp;&nbsp;Political' = > '3'
);

Upvotes: 1

Views: 2655

Answers (2)

Christian
Christian

Reputation: 28125

Since you want it quickly, here's a quick-n-dirty regex solution:

$matches = null;
$result = array();

if(preg_match_all('/value="(.*)".*?>(.*)<\\/option>/', $s, $result)){
    $matches = array_pop($matches);
    foreach($matches[1] as $i => $key){
        $key = html_entity_decode($key);
        $val = html_entity_decode($matches[2][$i]);
        $result[$key] = $val;
    }
}

print_r($result);

However, you really should not tokenise/parse HTML with regular expressions, instead use an XML/DOM class.

Upvotes: 1

Ilya
Ilya

Reputation: 4689

Try this:

$list = explode('</option>', $s);
foreach ($list as $v)
  $result[] = strip_tags($v);

Upvotes: 1

Related Questions