View Full Version : How to use preg_match_all to extract name="something"

01-20-2010, 04:25 AM
I have to admit, I don't get the preg_match_all syntax, looks confusing for me.

Here is what I want to do:

I have a HTML FORM and I want to extract what's inside the name="abcd"

So I input lots all HTML, and want to output abcd, and all other 'name' words.

Seems all web examples are just copied from php.net , but it's nowhere actually explained how to use it.

How can I do that in my case?

01-20-2010, 04:36 AM
preg_match_all('%\bname="([^"]+)%', $input_text, $matches);
echo '<pre>'.print_r($matches[1], true).'</pre>';The above regex looks for text that starts with name=" (without any letters before the word name) and then saves anything between the " up to any other " into $matches[1]

Below is the full explaination


Assert position at a word boundary «\b»
Match the characters “name="” literally «name="»
Match the regular expression below and capture its match into backreference number 1 «([^"]+)»
Match any character that is NOT a “"” «[^"]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

01-20-2010, 04:45 AM
Thanks. I get there slowly. Your samples outputs also name=", so I get i.e. name="price1

How can I prevent that?

And I forgot, sometimes there is also name=\"price1\"

You know any page where all the "'%\bname="([^"]+)%" options are explained? on php.net it seems to be implied knowledge.


01-20-2010, 05:07 AM
If you use $matches[1] it should only contain the contents between the ""
Take a look here for regex info

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum