Parsing the last substring of a URL

I want to parse the line after the last "/". For example:

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

      

Disassemble the "engine".

I tried to do it with Regexp, but as new to regexp that was next to the solution. Also this pattern seems to be quite easily destructible (/ engine / will break it). We need to make it a little more stable somehow.

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

      

  • / Match / char
  • ... + Matches any char, one or more
  • ^ [^ / \ Exclude \ char

Demonstration of the current state

+3


source to share


4 answers


You don't need regex, don't make it complicated, just use this:

<?php

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

?>

      



Output:

engine

      

+5


source


I recommend you use the performatner functions instead of preg_match to do this

for example basename ()

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

      



or explode ()

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

      

+1


source


You can also use parse_url () , explode () and array_pop () to achieve your goal.

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

+1


source


It is something?

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

      

Output:

engine

      

0


source







All Articles