Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
    
try \bname\b\s*=\s*"\K[^"]+(?=") –  Avinash Raj 39 mins ago
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. –  Andrei P. 39 mins ago
    
or use the DOMdocument::getElementsByTagName method and iterate through, grabbing the name property. –  S O 36 mins ago
    
Thanks Avinash, will have a look. Andrei, will look into HTML parsers, got a recommendation? S O, isn't that Javascript? –  Ryan 35 mins ago
1  
@Ryan PHP already has HTML parsers built-in with it. Take a look at DOMDocument of PHP –  Ghost 27 mins ago

2 Answers 2

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;
}
share

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 />";
}

?>
share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.