Japar S Japar S - 4 months ago 19
PHP Question

Extract Form Value PHP with preg_match?

I have get html page from other site using

file_get_contents
and i want to extract form value.Html is look like this:

<input type='hidden' name='csrfmiddlewaretoken' value='here'>


So,how i get
here
using
preg_replace


What i was tried so far:

preg_match_all("/'hidden' value='(.*?)'/",$html, $matches);

Doesn't not work!

Answer

Don't use regexes for parsing HTML. Use tools that are designed specifically for this.

$previous_value = libxml_use_internal_errors(TRUE);

$string ="<input type='hidden' name='csrfmiddlewaretoken' value='here'>";
$dom = new DOMDocument();
$dom->loadHTML($string);
$input = $dom->getElementsByTagName('input')->item(0);
echo $input->getAttribute("value");

libxml_clear_errors();
libxml_use_internal_errors($previous_value);

Demo