...

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



fail
01-20-2010, 03: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?

JAY6390
01-20-2010, 03: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


\bname="([^"]+)

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) «+»

fail
01-20-2010, 03: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.

http://php.net/manual/en/function.preg-match-all.php

JAY6390
01-20-2010, 04:07 AM
If you use $matches[1] it should only contain the contents between the ""
Take a look here for regex info
http://www.regular-expressions.info/



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum