1

I have many strings like these (HTML ones). Long select/option tags like the following.

<option value="93">Afghanistan (93)</option>
<option value="355">Albania (355)</option>
<option value="213">Algeria (213)</option>
<option value="376">Andorra (376)</option>
<option value="244">Angola (244)</option>
<option value="264">Anguilla (264)</option>

I intend to convert this into a PHP array like,

array("93"=>"Afghanistan (93)","355"=>"Albania (355)","213"=>"Algeria (213)", ...)

I've never worked on RegEx in PHP so don't know how to approach this. What code/functions should I be using to convert such data?

user987815
  • 11
  • 1

2 Answers2

1

This is a basic regular expression question.

preg_match_all("#\"(\d+)\">((\w+) \(\d+\))<#", $data, $m);
$result = array_combine($m[1], $m[2]);

But I think you need

preg_match_all("#(\d+)\">(\w+)#", $data, $m);
$result = array_combine($m[1], $m[2]);
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

Use:

preg_match_all('/<option value="([0-9]+)">(.*?)<\/option>/is', $data, $matches);

$result=array();
foreach($matches[1] as $key=>$value){
    $result[$value]=$matches[2][$key];
}
var_dump($result);

I suggest you to use DomDocument class for this kind of work. http://www.php.net/manual/fr/class.domdocument.php

Darm
  • 5,581
  • 2
  • 20
  • 18
  • +1 But instead of: `(.*?)` I'd use the more specific: `([^<]+\(\1\))`. Regex is perfectly ok to use with HTML when the target string is highly specific like this one. – ridgerunner Dec 11 '11 at 19:37