解析 url 的最后一个子串

Parsing the last substring of the url

我想解析最后一个“/”之后的字符串。 例如:

http://127.0.0.1/~dtm/index.php/en/parts/engine

解析 "engine" .

我尝试用正则表达式来做,但作为正则表达式的新手,我卡在了解决方案附近。 此外,这种模式似乎很容易破解(/engine/ 会破坏它)。需要以某种方式使其更稳定。

$pattern = ' \/(.+^[^\/]?) ' ;

Demo of the current state

您不需要正则表达式,不要让它变得复杂,只需使用它:

<?php

    $url = "http://127.0.0.1/~dtm/index.php/en/parts/engine";
    echo basename($url);

?>

输出:

engine

我建议您使用 performatner 函数而不是 preg_match 来执行此操作

例如 basename()

   $url = "http://127.0.0.1/~dtm/index.php/en/parts/engine";
   echo basename($url);

或爆炸()

  $parts = explode('/',$url);
  echo array_pop($parts);

您也可以同时使用 parse_url(), explode() and array_pop() 来实现您的目标。

<?php
$url = 'http://127.0.0.1/~dtm/index.php/en/parts/engine';
$parsed = parse_url($url);
$path = $parsed['path'];
echo array_pop(explode('/', $path));
?>

PhpFiddle Demo

这是什么东西吗?

$url = "http://127.0.0.1/~dtm/index.php/en/parts/engine";
$ending = end(explode('/', $url));

输出:

engine