RichieAHB
RichieAHB

Reputation: 2088

Match everything before last section of url

I want to match everything in a URL up to the last section.

So I want to match: http://www.test.com/one/two/ in all of the following cases:

http://www.test.com/one/two/three
http://www.test.com/one/two/three/
http://www.test.com/one/two/three/?foo=bar

I'm working in PHP and currently I have /.+\/(?=[^\/]+\/?$)/ this matches everything except the last case but I can't seem to 'not match a forward slash unless it's followed by a question mark' which would seeming sort the problem?

Upvotes: 0

Views: 82

Answers (2)

zx81
zx81

Reputation: 41838

Here you go, richieahb

The regex:

(?m)http://[^/]+(?:/[^/]+)*/(?!\?)(?=[^/\n]+)

The test (with one more level added)

<?php
$string = "http://www.test.com/one/two/three
http://www.test.com/one/two/three/
http://www.test.com/one/two/three/four
http://www.test.com/one/two/three/four/
http://www.test.com/one/two/three/?foo=barv";

$regex="~(?m)http://[^/]+(?:/[^/]+)*/(?!\?)(?=[^/\r\n]+)~";

preg_match_all($regex,$string,$m);

echo "<pre>";
print_r($m[0]);
echo "</pre>";
?>

The Output:

Array
(
    [0] => http://www.test.com/one/two/
    [1] => http://www.test.com/one/two/
    [2] => http://www.test.com/one/two/three/
    [3] => http://www.test.com/one/two/three/
    [4] => http://www.test.com/one/two/
)

Upvotes: 1

alreadycoded.com
alreadycoded.com

Reputation: 326

$text = 'http://www.test.com/one/two/three http://www.test.com/one/two/three/ http://www.test.com/one/two/three/?foo=bar';
preg_match_all('#http://(.*?)/(.*?)/(.*?)/#is', $text, $matches);
print_r($matches[0]);

Upvotes: 0

Related Questions