【问题标题】:PHP regex to remove last matching pattern stringPHP正则表达式删除最后一个匹配的模式字符串
【发布时间】:2013-12-04 06:05:20
【问题描述】:

我有以下网址

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...

使用preg regex,如何去掉右边的文件名?我想它需要从右边开始匹配第一个破折号,我该怎么做?

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

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

或使用

$newURL = preg_replace(...);

$newUrl 变量将只包含

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

在末尾保留斜杠。我可以通过使用 explode()、array_pop() 和 implode() 将它们重新组合在一起,只是想知道是否可以仅使用正则表达式。

谢谢。

【问题讨论】:

  • 如果你需要正则表达式免费解决方案,试试这个echo substr($link1,0,strrpos($link1,'/')+1);

标签: php regex preg-match


【解决方案1】:

您可以使用以下内容。

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

echo clean($url);

Live demo

使用正则表达式:

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

Live demo

【讨论】:

  • 非常感谢,这个 preg_replace 正是我想要的。
【解决方案2】:
<?php
$str = 'http://domain.com/baby/smile/love/index.txt';

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

输出:

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

【讨论】:

    【解决方案3】:

    这应该可行:

    $s = 'http://domain.com/baby/smile/love/index.txt';
    
    if (preg_match_all('~^.+?/(?!.*?/)~', $s, $matches))
            print_r ( $matches[0] );
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多