preg_match

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
smilesmita
Forum Commoner
Posts: 30
Joined: Thu May 24, 2007 1:52 pm

preg_match

Post 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
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Moved to Regex.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Post 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);
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post 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.
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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.
Post Reply