匹配URL的路径,减去文件扩展名

sil*_*min 11 regex nginx

这个场景的最佳正则表达式是什么?

鉴于此URL:

http://php.net/manual/en/function.preg-match.php
Run Code Online (Sandbox Code Playgroud)

我该如何选择(但不包括)http://php.net和之间的所有内容.php:

/manual/en/function.preg-match
Run Code Online (Sandbox Code Playgroud)

这是针对Nginx配置文件的.

小智 20

正则表达式可能不是这项工作最有效的工具.

尝试使用parse_url(),结合pathinfo():

$url      = 'http://php.net/manual/en/function.preg-match.php';
$path     = parse_url($url, PHP_URL_PATH);
$pathinfo = pathinfo($path);

echo $pathinfo['dirname'], '/', $pathinfo['filename'];
Run Code Online (Sandbox Code Playgroud)

以上代码输出:

/manual/en/function.preg-match


Fai*_*Dev 8

像这样:

if (preg_match('/(?<=net).*(?=\.php)/', $subject, $regs)) {
    $result = $regs[0];
}
Run Code Online (Sandbox Code Playgroud)

说明:

"
(?<=      # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
   net       # Match the characters “net” literally
)
.         # Match any single character that is not a line break character
   *         # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?=       # Assert that the regex below can be matched, starting at this position (positive lookahead)
   \.        # Match the character “.” literally
   php       # Match the characters “php” literally
)
"
Run Code Online (Sandbox Code Playgroud)

  • `'/ net(.*)\ .php /'`,更简单,更短(也可能更好)同一表达式的版本.(我更喜欢表达而没有浪费的不必要的外观.) (3认同)