Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading attribute values from HTML

I have HTML stored in a string. The markup contains form input fields called initval and endval which are the value attribute values I need. How can I get them from this string markup?

<form id="compute">
   <input type="hidden" name="initval" value="tal:00far" />
   <input type="hidden" name="endval" value="utl:80er" />
</form>
like image 999
sami Avatar asked Jul 14 '26 03:07

sami


1 Answers

Presuming that the structure is very reliably like that, try the following:

$htmlCode = "...";
$matches = array();

if (preg_match_all('/name="(initval|endval)"\s+value="([^"]+)"/', $htmlCode, $matches)) {
    $formValues = array_combine($matches[1], $matches[2]);
} else {
   // error
}

This assumes only whitespace between the name and value attributes, you'll need to make a small change if it differs. preg_match_all() returns an array with the whole regexp match at [0], and then the individual group matches in their corresponding locations [1] & [2], the array combine takes one as keys, one as values and puts it together so you have an associative lookup to get your results.

like image 172
Orbling Avatar answered Jul 21 '26 10:07

Orbling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!