Regex for this?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Regex for this?

Post by mjseaden »

Dear All,

I have an URL address of the form

/string/anotherstring/yetanotherstring21

Any number of /strings/ can occur in the address - can anyone tell me if I can

[a] Detect whether or not a number has occurred after 'yetanotherstring'

and if so

Extract this number into a variable

Sometimes, a number will not appear at the end and therefore this case needs to be discounted.

Many thanks

Mark
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

untested

Code: Select all

preg_match_all('#/\w*((\d+)\w*)*$#',$url,$matches)
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

seems like it should work... just add the literal slash after the first asterisk.
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

Hi feyd/weirdan - thanks for the response. It doesn't seem to be working I'm afraid. I'm using the following PHP code:

Code: Select all

// Check if a property information page is called via /<type>X
if( preg_match('#/\w*((\d+)\w*)*$#',$url,$match2) && $pagecall != true )
{
    if(!empty($match2[1]))
    {
        $propcall = true;
        echo 'Property Info: '.$match2[2];
    }
}
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

It doesn't seem to detect the URL properly. If I add a ''' before the first *, it reports an unmatched parentheses error.
mjseaden
Forum Contributor
Posts: 458
Joined: Wed Mar 17, 2004 5:49 am

Post by mjseaden »

Hi there - can anyone help?

Many thanks

Mark
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

I'd just do:

Code: Select all

preg_match('#[0-9]*$#', basename($url), $match);
if(!empty($match[0])){
  echo $match[0]; //it did have a number on the end
} else {
  echo 'no ending numbers';
}
Post Reply