Simple Regex question

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

Moderator: General Moderators

Post Reply
ChrisF79
Forum Commoner
Posts: 26
Joined: Tue Apr 01, 2008 8:26 pm

Simple Regex question

Post by ChrisF79 »

I'm really hoping someone can help here.

How would I search $string below and store 208046194 in a variable that I can work with?

$string = '<td width=85 align=left valign=top class='label'>ML#:</td><td width=175 align=left valign=top>208046194</td>';

Thanks so much in advance for the help!
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Simple Regex question

Post by Benjamin »

Code: Select all

 
if (preg_match('#>\s{0,3}(\d{3,})\s{0,3}<#', $string, $match)) {
    echo $match[1];
}
 
This assumes that the number will always be 3 or more digits long. You can change the {3,} to more or less.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Simple Regex question

Post by prometheuzz »

astions wrote:

Code: Select all

 
if (preg_match('#>\s{0,3}(\d{3,})\s{0,3}<#', $string, $match)) {
    echo $match[1];
}
 
This assumes that the number will always be 3 or more digits long. You can change the {3,} to more or less.
Why the "\s{0,3}"?

Edit: nvm, I didn't see the '>' before and '<' after these "\s{0,3}". Still, I'd opt for "\s*" instead.
Last edited by prometheuzz on Fri Feb 20, 2009 1:12 am, edited 1 time in total.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Simple Regex question

Post by Benjamin »

The regex doesn't assume there will never be spaces on either side of the digits.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Simple Regex question

Post by prometheuzz »

astions wrote:The regex doesn't assume there will never be spaces on either side of the digits.
Wow, your'e fast!
; )
Post Reply