PHP正则表达式删除最后匹配的模式字符串

时间:2022-09-13 12:24:54

I have following URLs

我有以下网址

http://domain.com/baby/smile/love/index.txt
http://domain.com/baby/smile/love/toy.txt
http://domain.com/baby/smile/love/car.html
and so on...

using preg regex, how to remove the file name on the right? I guess it's required to match the first dash starting from the right, how I can do this?

使用preg正则表达式,如何删除右侧的文件名?我想从右边开始需要匹配第一个破折号,我该怎么做?

So for example if I run something like

例如,如果我运行类似的东西

$newUrl = preg_match('xxxxxx', '', $url);

$ newUrl = preg_match('xxxxxx','',$ url);

or using

$newURL = preg_replace(...);

The $newUrl variable will only contain

$ newUrl变量只包含

http://domain.com/baby/smile/love/

preserving the trailing slash at the end. I was able to do it by using explode(), array_pop(), then implode() to put it back together, just wondering if it 's possible using only regex.

最后保留尾部斜杠。我能够通过使用explode(),array_pop(),然后使用implode()将它重新组合在一起,只是想知道是否可以只使用正则表达式。

Thank you.

3 个解决方案

#1


4  

You can use the following.

您可以使用以下内容。

function clean($url) {
   $link = substr(strrchr($url, '/'), 1);
   return substr($url, 0, - strlen($link));
}

echo clean($url);

See Live demo

查看现场演示

Using regular expression:

使用正则表达式:

$newUrl = preg_replace('~[^/]*$~', '', $url);

See Live demo

查看现场演示

#2


3  

<?php
$str = 'http://domain.com/baby/smile/love/index.txt';

$str = preg_replace('/(.*\/).*/', '$1', $str);
print $str;

Output:

http://domain.com/baby/smile/love/

#3


1  

This should work:

这应该工作:

$s = 'http://domain.com/baby/smile/love/index.txt';

if (preg_match_all('~^.+?/(?!.*?/)~', $s, $matches))
        print_r ( $matches[0] );

OUTPU:

Array
(
    [0] => http://domain.com/baby/smile/love/
)

#1


4  

You can use the following.

您可以使用以下内容。

function clean($url) {
   $link = substr(strrchr($url, '/'), 1);
   return substr($url, 0, - strlen($link));
}

echo clean($url);

See Live demo

查看现场演示

Using regular expression:

使用正则表达式:

$newUrl = preg_replace('~[^/]*$~', '', $url);

See Live demo

查看现场演示

#2


3  

<?php
$str = 'http://domain.com/baby/smile/love/index.txt';

$str = preg_replace('/(.*\/).*/', '$1', $str);
print $str;

Output:

http://domain.com/baby/smile/love/

#3


1  

This should work:

这应该工作:

$s = 'http://domain.com/baby/smile/love/index.txt';

if (preg_match_all('~^.+?/(?!.*?/)~', $s, $matches))
        print_r ( $matches[0] );

OUTPU:

Array
(
    [0] => http://domain.com/baby/smile/love/
)