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="com开发者_如何学Cpute">
<input type="hidden" name="initval" value="tal:00far" />
<input type="hidden" name="endval" value="utl:80er" />
</form>
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.
If I have got your question right, In HTML
<form id="compute" action="somefile.php" method="GET">
<input type="hidden" name="initval" value="tal:00far" />
<input type="hidden" name="endval" value="utl:80er" />
<input type="submit" value="Click!">
</form>
Upon clicking submit the data is sent the the php script, where it can be read as
$initval = $_GET['initval'];
$endval =$_GET['endval'];
EDIT: It seems I have got the question wrong, Sorry. :-(
Try Using htmldomlibraries for parsing html.
精彩评论