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

时间:2014-04-26 11:08:50

标签: php regex

我希望将网址中的所有内容与最后一部分进行匹配。

所以我希望在以下所有情况下匹配: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,目前我/.+\/(?=[^\/]+\/?$)/这个匹配除了最后一个案例之外的所有内容但我似乎'不匹配正斜杠,除非它后跟一个问号'看似排序问题?

2 个答案:

答案 0 :(得分:1)

你去,richieahb

正则表达式:

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

测试(添加了一个级别)

<?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/
)

答案 1 :(得分:0)

$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]);