tags:

views:

289

answers:

2

I'm looking to extract values from a whole load of html (i've just trimmed down to the relevant data), there are multiple 'select' elements, and only want to extract those who's 'name' element matches the name 'aMembers'. So the resulting values I would like to retrieve are 5,10,25 and 30 (see below) how can I achieve this with preg_match?

    <DIV id="searchM" class="search"><select name="aMembers" id="aMembers" tabIndex="2">
    <option selected="selected" value="">Data 3</option>
    <option value="5">A name</option>
    <option value="10">Another name</option>
</select>
</DIV>
<DIV id="searchM" class="search"><select name="bMembers" id="bMembers" tabIndex="2">
    <option selected="selected" value="">Data 2</option>
    <option value="15">A name</option>
    <option value="20">Another name</option>
</select>
</DIV>
<DIV id="searchM" class="search"><select name="aMembers" id="Members" tabIndex="2">
    <option selected="selected" value="">Data 1</option>
    <option value="25">A name</option>
    <option value="30">Another name</option>
</select>
</DIV>
A: 

Using preg_match for this will result in a fragile solution. I recommend looking into parsing this with a proper HTML parser, or using a library like jQuery to select the elements you're interested in.

Bart Kiers
A: 

I would try to split this task into 2 steps:

  1. matching needed tags
  2. matching needed values in them

This way would be easier:

$str = 'your HTML code here...';
preg_match_all('|<select name="aMembers".*?</select>|ms', $str, $matches);
foreach ($matches[0] as $select) {
    preg_match_all('|value="(.+?)"|', $select, $matches2);
    var_dump($matches2[1]);
}
Laimoncijus