Matching fixed URI's

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

Moderator: General Moderators

mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Re: Matching fixed URI's

Post by mintedjo »

I dont really understand xP
Cant you use split() ?
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Matching fixed URI's

Post by alex.barylski »

I think I have my regex figured out, finally :)

Code: Select all

#^([^/]+)/([^\.|/]+)\.([^\?|/]+)(.*)#
URI = food/apples.html

Results in

Code: Select all

[0] = food
[1] = apples
[2] = html
However one nagging fact I would like to fix is the fact if I append a query string to the end, like:

URI = food/apples.html?name=value&name=value

The results are then

Code: Select all

[0] = food
[1] = apples
[2] = html
[3] = ?name=value&name=value
 
Ideally the last element would *not* contain the '?' but the catch is it needs to be optional

Any ideas?
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Matching fixed URI's

Post by prometheuzz »

PCSpectra wrote:Update: I have tried the following regex:

Code: Select all

#([^/]+)/([^\?|/]+)([^\?|/]{0,}.*)#
It works but STILL includes the ? or / in the trailing group, which is what I want to ideally leave out of the final group, but the ? or / and everything after the main URI MUST be optional...

What am I doing wrong? :(
Why do you think the '?' should NOT be included? You're matching your entire string, so the '?' is a part of it (thus it ends up in your $matches). You should split on some delimiters instead so they are "removed" from your string.
Here's a slight modification on my previous suggestion (which worked fine up until you posted a different format of your url's, btw):

Code: Select all

<?php
$tests = array(
  "/food/apples/",
  "food/apples?name=value&name=value",
  "food/apples/index(10).html",
  "food/apples/index.html"
);
$delimiters = "/().?";
foreach($tests as $t) {
  if(preg_match('#^/?([^/]*/)*.*$#', $t)) {
    print_r(preg_split("#[{$delimiters}]+#", preg_replace('#^/|/$#', '', $t)));
  }
}
?>
Feel free to ask a specific question if all is not clear.

Good luck!
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Matching fixed URI's

Post by papa »

Nice one prometheuzz, my rexexp $tests got longer and longer :)
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Matching fixed URI's

Post by prometheuzz »

papa wrote:Nice one prometheuzz, my rexexp $tests got longer and longer :)
Thanks!
; )
mintedjo
Forum Contributor
Posts: 153
Joined: Wed Nov 19, 2008 6:23 am

Re: Matching fixed URI's

Post by mintedjo »

Deleted :-D

Didnt realise it had been answered already
Post Reply