1

I'm still very much learning Regex and I suck at it :(

I am getting an external webpage, saving it to a local file. The page contains a form, now I need to find all the form's input's names and put it into an array, for example:

<input type="text" name="firstName">

or

<input type="text" name="firstName" class="something">

from the above I just need firstName to go into my array.

To complicate matters just a little bit, I have noticed people writing it a bit different sometimes because of the space character, like so:

name= "firstName"
name = "firstName"
name ="firstName"

As I am still learning, I would really appreciate it if you could explain your regex

7
  • try \bname\b\s*=\s*"\K[^"]+(?=") Commented Mar 25, 2015 at 12:33
  • 5
    Do̴n͟'̡t p͞ar͜se ͟H̀T̶ML̶ ̸w͟ít͏h ͡r̡e͜g͘ex͟.͢. Use a HTML parser instead. For a relatively small amount of HTML it's ok, but not for what you want to achieve. Commented Mar 25, 2015 at 12:33
  • or use the DOMdocument::getElementsByTagName method and iterate through, grabbing the name property. Commented Mar 25, 2015 at 12:36
  • Thanks Avinash, will have a look. Andrei, will look into HTML parsers, got a recommendation? S O, isn't that Javascript? Commented Mar 25, 2015 at 12:37
  • 1
    @Ryan PHP already has HTML parsers built-in with it. Take a look at DOMDocument of PHP Commented Mar 25, 2015 at 12:45

2 Answers 2

1

Quick example:

<?PHP

$myDocument = new DOMDocument;
$myDocument->loadHTMLfile('example_page.html');

// Get form item(s)
$formItems = $myDocument->getElementsByTagName('form');

// Get input items from first form item
$inputItems = $formItems->items(0)->getElementsByTagName('input');

// Name attributes
foreach ($inputItems as $inputName) {
     echo $inputName->getAttribute('name') . "<br />";
}

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Using your example I get" Fatal error: Call to undefined method DOMNodeList::items()", this is the line $inputItems = $formItems->items(0)->getElementsByTagName('input');
1

You can use something like

$xmldoc = new DOMDocument();
$xmldoc->load('REQUIRED_URL');
foreach ($xmldoc->getElementsByTagName('form') as $formitem) {
    $inputnodes = $formitem->getElementsByTagName('input');
    $name = $inputnodes->item(0)->getAttribute('name');
    echo $name;
}

1 Comment

I keep getting this warning (and no output other than this warning) Warning: DOMDocument::load(): Opening and ending tag mismatch: link line 7 and head in ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.