Japar S
Japar S

Reputation: 49

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!

Upvotes: 1

Views: 778

Answers (2)

John Conde
John Conde

Reputation: 219874

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

Upvotes: 3

Jan
Jan

Reputation: 43169

As said in the comments, use a DOM parser instead:

<?php

$data = <<<DATA
<input type='hidden' name='csrfmiddlewaretoken' value='here'>
DATA;

$dom = new DOMDocument();
$dom->loadHTML($data);

$xpath = new DOMXPath($dom);

$input = $xpath->query("//input[@name = 'csrfmiddlewaretoken']/@value")->item(0)->nodeValue;
echo $input;
# here
?>

Upvotes: 2

Related Questions