Preg_match_all, get the values of the attributes name of the inputs

2

I'm doing a project with dynamic forms, that is, the user (administrator) can make their own form (HTML / CSS), but when I go to get the form to the database I need to check if the names ( name ) of inputs match the names of the completed form by the end user.

Example of a form stored in the database:

name: <input required name="name" type="text"><br>\r\n
nif: <input name="nif" type="text"><br>\r\n
<input type="submit" value="ENVIAR YO">

I would like to get the values of all attributes name , remembering also (since it can not be predicted) that both can be stored with "" ( name="email" ) or '' ( name='email' ), the regex must cover both cases

    
asked by anonymous 22.09.2016 / 19:15

1 answer

1

As mentioned in comment, you can in addition to regular expressions, use DOMDocument to represent the HTML and get your values.

Assuming you have the following HTML:

<form method="post" action="">
    <input type="hidden" name="produto1" value="teste1">
    <input type="hidden" name='produto2' value="teste2">
    <input name="produto3" type="hidden" value="teste3">
    <input type="hidden" name='produto4' value="teste4">
    <input type="hidden" name="produto5" value="teste5">  

<input type="submit" value="enviar">
</form>

Regular Expression

You can use the following regular expression: input.*(?<=name=['|"])(\w+) :

preg_match_all('-input.*(?<=name=[\'|"])(\w+)-', $html, $inputs);

See DEMO

Where:

  • input : Matches the word literally.
  • .* : Any character, except line break.
  • (?<=name=['|"])(\w+) : Positive Lookbehind . It will match characters that are in the range a-zA-Z0-9_ only if they are preceded by name= and ' or " .

DOM

With DOMDocument you can use DOMDocument::getElementsByTagName to select all HTML elements when specifying the tag:

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

$inputs = $dom->getElementsByTagName('input');

To return the names of the selected elements use DOMElement::getAttribute :

foreach ($inputs as $input) {
    echo $input->getAttribute('name') . "\n";
}

See DEMO

    
27.09.2016 / 19:55