1

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'
);
Hady Shaltout
  • 606
  • 1
  • 9
  • 22

2 Answers2

1

Try this:

$list = explode('</option>', $s);
foreach ($list as $v)
  $result[] = strip_tags($v);
Ilya
  • 4,583
  • 4
  • 26
  • 51
1

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.

Community
  • 1
  • 1
Christian
  • 27,509
  • 17
  • 111
  • 155
  • Thanks man so much, but the array repeated 3 times ** Array ( [0] => Array ( [0] => value="0">Recent Posts [1] => value="1">Uncategorized [2] => value="2">World News [3] => value="3"> Political [4] => value="4"> Economy ) [1] => Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 ) [2] => Array ( [0] => Recent Posts [1] => Uncategorized [2] => World News [3] => Political [4] => Economy ) ) ** can u help me with XML/DOM ?? – Hady Shaltout Aug 27 '13 at 06:52