Preg_match_all, get input name attribute values

Asked

Viewed 68 times

2

I am doing a project with dynamic forms, that is, the user (administrator) can make his own form (HTML/CSS), but when fetching the form from the database I need to check if the names (name) of inputs match the names of the form completed 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 fetch the values of all attributes name, remembering also (as it is not predictable) that both may be stored with "" (name="email") or with '' (name='email'), the regex should cover both cases

  • The user writes the HTML, or just gives the name of the fields?

  • Administrator inserts HTML @Papacharlie

  • Would it be something like, "name field html is :"? , it would always be relative to field or it could have "form html"?

  • @Miguel Com regex i think you can do something like this: https://regex101.com/r/sA2sM5/1. Why don’t you use Dom? see: http://ideone.com/xlrXGt

  • Obgado @stderr, I think you should answer, both are correct, you can put both. https://regex101.com/r/sA2sM5/2

1 answer

1


As mentioned in comment, you can in addition to regular expressions, use DOMDocument to represent HTML and get its 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: Corresponds literally to the word.
  • .*: Any character, except line break.
  • (?<=name=['|"])(\w+): Positive lookbehind. Will match the characters in the range a-zA-Z0-9_ only if preceded by name= and ' or ".

GIFT

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

  • However I managed to go around in another way. But of course this answers and well to the question. Obgado

Browser other questions tagged

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