Php 匹配url最后一部分之前的所有内容

Php 匹配url最后一部分之前的所有内容,php,regex,Php,Regex,我想将URL中的所有内容匹配到最后一节 所以我想匹配:http://www.test.com/one/two/在以下所有情况下: http://www.test.com/one/two/three http://www.test.com/one/two/three/ http://www.test.com/one/two/three/?foo=bar 我在PHP中工作,目前我有/.+\/(?=[^\/]+\/?$)/这匹配除最后一个案例外的所有情况,但我似乎不能“不匹配正斜杠,除非它后面有问号

我想将URL中的所有内容匹配到最后一节

所以我想匹配:
http://www.test.com/one/two/
在以下所有情况下:

http://www.test.com/one/two/three
http://www.test.com/one/two/three/
http://www.test.com/one/two/three/?foo=bar
我在PHP中工作,目前我有
/.+\/(?=[^\/]+\/?$)/
这匹配除最后一个案例外的所有情况,但我似乎不能“不匹配正斜杠,除非它后面有问号”,这似乎可以解决问题?

给你,richieahb

$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]);
正则表达式:

(?m)http://[^/]+(?:/[^/]+)*/(?!\?)(?=[^/\n]+)
测试(增加一个级别)


为什么不直接使用?
parse_url
不会将路径名拆分为dir,这似乎是OP想要的。我可以使用parse_url,然后用一个更简单的正则表达式删除最后一部分,但我想我会尝试只使用一个正则表达式。对于url层次结构中其他级别的任何内容,这都会失败。这应该适用于所有可能的URL。
<?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>";
?>
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/
)