1

See the below list of options, i am trying to get value of option which is selected.

<select>
  <option {class='test'} value="volvo" selected='selected'>Volvo</option>
  <option {class='test'} value="saab">Saab</option>
  <option {class='test'} value="mercedes">Mercedes</option>
  <option {class='test'}value="audi">Audi</option>
</select> 

in the above example i need to get volvo as the matched string. there may or may not have any class parameter. That's if option string is

<option {class='test'} value="volvo" selected='selected'>Volvo</option>

or

 <option value="volvo" selected='selected'>Volvo</option>

Regular expression should return volvo. That's a regular expression suitable for all cases.

I tried with

preg_match_all('/<option\sclass="[^"]*"\svalue="([^"]*)">([^>]*)<\/option>/', $string, $matches);`

But that didn't return value of the selected item. Please help.

Guillermo Gutiérrez
  • 17,273
  • 17
  • 89
  • 116
user866933
  • 305
  • 1
  • 6
  • 16

1 Answers1

0

Try this:

$re = '/^.*\<option.*value=(?:\'|")([a-z]*)(?:\'|").*(?=selected=(?:\'|")selected(?:\'|")).*$/m';

$str = '<select>\n  <option {class=\'test\'} value="volvo" selected=\'selected\'>Volvo</option>\n  <option {class=\'test\'} value="saab">Saab</option>\n  <option {class=\'test\'} value="mercedes">Mercedes</option>\n  <option {class=\'test\'} value="audi">Audi</option>\n</select> '; 

preg_match_all($re, $str, $matches);

echo "<pre>";
var_dump($matches);

I changed the logic of the expression from this:

/<option\sclass="[^"]*"\svalue="([^"]*)">([^>]*)<\/option>/

to this:

/^.*\<option.*value=(?:\'|")([a-z]*)(?:\'|").*(?=selected=(?:\'|")selected(?:\'|")).*$/m

and worked fine. See the regex101 example

However I really don't recommend regex for parsing html. I think you should take a look into other ways to accomplish your task, eg. how-do-you-parse-and-process-html-xml-in-php

Community
  • 1
  • 1
Caio Oliveira
  • 1,243
  • 13
  • 22