简体   繁体   中英

preg_match in php for select tags

I want to get all options value between below select tags using preg_match

<select id="current-statement" name="current-statement" data-reactid=".4.2.2.1.0.2.1.1.0">
<option value="current" data-reactid=".4.2.2.1.0.2.1.1.0.0">Current Statement</option>
<option value="90989266-c853-289b-dfea-3cdfe2213db7" data-reactid=".4.2.2.1.0.2.1.1.0.1">1st Statement</option>
<option value="165eb5ea-fd48-53c8-020b-6e3287859922" data-reactid=".4.2.2.1.0.2.1.1.0.2">second statement</option>
<option value="0d558fa0-8f48-afa2-7a9a-e8f85fbbbc42" data-reactid=".4.2.2.1.0.2.1.1.0.3">third statement</option>
<option value="9c78f8aa-3b09-4574-1c10-8f450b45eb5b" data-reactid=".2.0.0.1.0.2.1.1.0.4">4th statement</option>
</select>

I am trying to get it like following preg_match but unable to do so

preg_match("'<select id=\"current-statement\" name=\"current-statement\" data-reactid=\".4.2.2.1.0.2.1.1.0\">(.*?)</select>'", $content, $match);

if($match) echo "result=".$match[1];

Please help

With DOM, the task is reduced to writing a working XPath expression:

//select/*/text()

where

  • //select - find all select tags
    • /* - then any child inside
      • /text() - and fetch the text nodes.

See PHP demo :

$html = <<<DATA
<select id="current-statement" name="current-statement" data-reactid=".4.2.2.1.0.2.1.1.0">
<option value="current" data-reactid=".4.2.2.1.0.2.1.1.0.0">Current Statement</option>
<option value="90989266-c853-289b-dfea-3cdfe2213db7" data-reactid=".4.2.2.1.0.2.1.1.0.1">1st Statement</option>
<option value="165eb5ea-fd48-53c8-020b-6e3287859922" data-reactid=".4.2.2.1.0.2.1.1.0.2">second statement</option>
<option value="0d558fa0-8f48-afa2-7a9a-e8f85fbbbc42" data-reactid=".4.2.2.1.0.2.1.1.0.3">third statement</option>
<option value="9c78f8aa-3b09-4574-1c10-8f450b45eb5b" data-reactid=".2.0.0.1.0.2.1.1.0.4">4th statement</option>
</select>
DATA;

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$xpath = new DOMXPath($dom);
$opts = $xpath->query('//select/*/text()');
$res = array();
foreach($opts as $opt) { 
   array_push($res, $opt->nodeValue);
}
print_r($res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM