preg_match
Moderator: General Moderators
-
smilesmita
- Forum Commoner
- Posts: 30
- Joined: Thu May 24, 2007 1:52 pm
preg_match
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
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
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
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 
You may also be interested in viewtopic.php?t=33147 and viewtopic.php?t=40169
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.Jcart wrote:Code: Select all
preg_match('#([0-9\.]+)#', $source, $matches);
Code: Select all
preg_match('#[0-9.]+#', $source, $matches);- stereofrog
- Forum Contributor
- Posts: 386
- Joined: Mon Dec 04, 2006 6:10 am
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.
[\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.
More strict expressions:
Decimals optional:
Decimals required:
In case of being more strict and only looking for numbers with exactly two decimal digits:
Hope this helps.
Decimals optional:
Code: Select all
#[0-9]+(\.[0-9]+)?#Code: Select all
#[0-9]+\.[0-9]+#Code: Select all
#[0-9]+\.[0-9]{2}#- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Interesting.GeertDD wrote: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.Jcart wrote:Code: Select all
preg_match('#([0-9\.]+)#', $source, $matches);
Code: Select all
preg_match('#[0-9.]+#', $source, $matches);