user2650277 user2650277 - 8 months ago 49
PHP Question

Getting hidden input values with preg_match

I am trying to get the value of

_fh
and
_nonce
with
preg_match


HTML

<form method="post" enctype="multipart/form-data" name="signin">
<input type="hidden" name="_fh" value="cd5a29509482534507a7a999ad0e0943">
<input type="hidden" name="_nonce" value="7fe456a0902ba89b365f760cdeb37113">


Here is my attempt

$returnValue = preg_match('#<input(.*)name="_fh"(.*)value="(.*?)"#is', '<form method="post" enctype="multipart/form-data" name="signin">
<input type="hidden" name="_fh" value="cd5a29509482534507a7a999ad0e0943">
<input type="hidden" name="_nonce" value="7fe456a0902ba89b365f760cdeb37113">

', $matches);


Result

array (
0 => '<input type="hidden" name="_fh" value="cd5a29509482534507a7a999ad0e0943">
<input type="hidden" name="_nonce" value="7fe456a0902ba89b365f760cdeb37113"',
1 => ' type="hidden" ',
2 => ' value="cd5a29509482534507a7a999ad0e0943">
<input type="hidden" name="_nonce" ',
3 => '7fe456a0902ba89b365f760cdeb37113',
)

Answer Source

Don't use regex for parsing HTML.

Recommended is to use HTML DOM parser like this:

$html = <<<EOF
<form method="post" enctype="multipart/form-data"  name="signin">
<input type="hidden" name="_fh" value="cd5a29509482534507a7a999ad0e0943">
<input type="hidden" name="_nonce" value="7fe456a0902ba89b365f760cdeb37113">
EOF;

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);

#echo $doc->saveHTML();
$xpath = new DOMXPath($doc);

$val1 = $xpath->query('//input[@name="_fh"]/@value')->item(0)->nodeValue;

$val2 = $xpath->query('//input[@name="_nonce"]/@value')->item(0)->nodeValue;

echo $val1 . PHP_EOL;
echo $val2 . PHP_EOL;

Output:

cd5a29509482534507a7a999ad0e0943
7fe456a0902ba89b365f760cdeb37113