Take name via regex

Asked

Viewed 54 times

0

How can I get the name of this input via regex(preg_match_all) ?

<input type="hidden" name="84a99a062288829a0f72271afea83ee9" value="_nc" />
  • 1

    preg_match_all('/<input[^>*]*name="(.*?)"[^*]*value="_nc"[^*]*>/', $html, $result); var_dump($result);

  • 1

    @Valdeirpsr DOMDocument opens doors :)

  • @Guilhermenascimento Agree, including use in some situations, but depending on the case, with a simple regex leaves the code clean.

  • @Valdeirpsr not so much, even more if it is to compare 6/7 lines with 4 lines (counting preg_match + if + var).

  • Take it easy there, c0d3rs. kkkkkkkk

2 answers

1


I think the best way is to use DOMDocument PHP, which is properly for working with HTML, example:

$get = '<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<input type="hidden" name="84a99a062288829a0f72271afea83ee9" value="_nc" />
<input type="hidden" name="foo" value="bar" />
<input type="hidden" name="baz" value="boo" />
<input type="hidden" name="foobar" value="bazbar" />
</body>
</html>';

$doc = new DOMDocument();
$doc->loadHTML($get);

$allInputs = $doc->getElementsByTagName('input');
foreach ($allInputs as $input) {
    echo $input->getAttribute('name'), '<br>';
}

If you want to take only the element that has the value _nc, make an if:

$valor = null;    
$allInputs = $doc->getElementsByTagName('input');

foreach ($allInputs as $input) {
    if ($input->getAttribute('value') == '_nc') {
        $valor = $input->getAttribute('name'), '<br>';
    }
}

echo 'Valor do input:', $valor;

Or use DOMXpath:

$doc = new DOMDocument();
$doc->loadHTML($get);

$xpath = new DOMXpath($doc);

$valor = null;
$allInputs = $xpath->query("*/input[@value='_nc']");

foreach ($allInputs as $input) {
    $valor = $input->getAttribute('name'), '<br>';
}

echo 'Valor do input:', $valor;

Similar to what I answered in /a/59526/3635

0

Use the match (?:name=) "( w*)\" and take the first group.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.