Regex删除URL中第4个斜杠后的所有内容


Regex to Remove Everything After 4th Slash in URL

我在PHP中使用友好的URL路径,格式为:

/2011/09/here-is-the-title
/2011/09/here-is-the-title/2

我需要标准化这些URL路径,以删除4斜杠之后的任何内容,包括斜杠本身。第四个斜线后面的值有时是一个数字,但也可以是任何参数。

有没有想过我该怎么做?我想regex可以处理它,但我很糟糕。我还认为strpossubstr的组合可能能够处理它,但是无法完全解决。

您可以使用explode()函数:

$parts  = explode('/', '/2011/09/here-is-the-title/2');
$output = implode('/', array_slice($parts, 0, 4));

更换

%^((/[^/]*){3}).*%g

1美元。

参见http://regexr.com?2vlr8对于实际示例

如果您的regex实现支持任意长度的look-behind断言,则可以替换

(?<=^[^/]*(/[^/]*){3})/.*$

带有一个空字符串。如果没有,您可以更换

 ^([^/]*(?:/[^/]*){3})/.*$

具有第一捕捉组的内容。第二个例子的PHP示例可以在ideone.com上找到。

您也可以使用循环:

result="";
for char c in URL:
    if(c is a slash) count++;
    if(count<4) result=result+c;
    else break;