Page 1 of 1

preg_match

Posted: Thu Aug 30, 2007 2:32 pm
by smilesmita
hi there:

i have somethig like this in my buff:
<TD>Average Rate</TD><TD align="right">31.09</TD>

i want to apply preg_match to get the value 31.09 out..how do it do it?>

please help!

-smita

Posted: Thu Aug 30, 2007 3:03 pm
by John Cartwright
Moved to Regex.

Posted: Thu Aug 30, 2007 5:52 pm
by John Cartwright
This will get you started, given your sample html.. however I get the feeling it's not going to work the way you expect if you apply this against a full html page of markup. Play around with this sample and post what you've tried, after all this should be a learning experience ;)

Code: Select all

preg_match('#([0-9\.]+)#', $source, $matches);
You may also be interested in viewtopic.php?t=33147 and viewtopic.php?t=40169

Posted: Sun Sep 02, 2007 4:37 am
by GeertDD
Jcart wrote:

Code: Select all

preg_match('#([0-9\.]+)#', $source, $matches);
There's no need to wrap the full regex in capturing parentheses. It will only slow things down. Also the dot does not need to be escaped inside a character class.

Code: Select all

preg_match('#[0-9.]+#', $source, $matches);

Posted: Sun Sep 02, 2007 5:02 am
by stereofrog
There's an interesting psychological twist with regexp ranges. For some reason, most people tend to think (more or less unconsciously) that "[AB]+" denotes a string consisting of both A _and_ B, while actually one A _or_ B is sufficient for the pattern to match.

[\d.] will, of course, match 12.3, but it will also match a string of 100 dots or similar. I'm sure that's not what OP asked.

Posted: Sun Sep 02, 2007 6:05 am
by vigge89
More strict expressions:
Decimals optional:

Code: Select all

#[0-9]+(\.[0-9]+)?#
Decimals required:

Code: Select all

#[0-9]+\.[0-9]+#
In case of being more strict and only looking for numbers with exactly two decimal digits:

Code: Select all

#[0-9]+\.[0-9]{2}#
Hope this helps.

Posted: Fri Sep 07, 2007 8:58 am
by John Cartwright
GeertDD wrote:
Jcart wrote:

Code: Select all

preg_match('#([0-9\.]+)#', $source, $matches);
There's no need to wrap the full regex in capturing parentheses. It will only slow things down. Also the dot does not need to be escaped inside a character class.

Code: Select all

preg_match('#[0-9.]+#', $source, $matches);
Interesting.