3

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

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

Parse the "engine" .

I tried do it with Regexp but as im new to regexp im stuck near the solution. Also this pattern seems quite easy breakable (/engine/ will break it ) . Need somehow make it a bit more stable.

$pattern = ' \/(.+^[^\/]?) ' ;
  • / Match the / char
  • .+ Match any char one or more times
  • ^[^/\ Exclude \ char

Demo of the current state

IseNgaRt
  • 601
  • 1
  • 4
  • 22
  • Check this out: http://stackoverflow.com/questions/19776979/regex-get-all-characters-after-last-slash-in-url – rebyte Jan 07 '15 at 14:11
  • **1** You have some spaces in your regex that probably shouldn't be there. **2** `^` (outside of a class) means beginning of string so it makes no sense to have it in the middle of a regex like that. **3** `.+[^\/]?` means some characters of any kind (`/` included) followed by an optional single character that is not `/` (so the whole thing can be shortened to `.+`). Perhaps a regex tutorial would be a good start. – Biffen Jan 07 '15 at 14:11
  • 1
    `basename` is probably your best bet. `explode` + `end` or `array_pop`. `parse_url` might be useful, too. Really no need for regex _at all_ – Elias Van Ootegem Jan 07 '15 at 14:18

4 Answers4

5

You don't need a 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
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • I searched for any premade functions that could do that, but dunno why i didnt find something about basename. Thanks dude ! This is sure way easier, better than regexp. – IseNgaRt Jan 07 '15 at 14:26
1

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

eg 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);
donald123
  • 5,638
  • 3
  • 26
  • 23
1

You can also use parse_url(), explode() and array_pop() together 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

Sithu
  • 4,752
  • 9
  • 64
  • 110
0

Is this something?

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

Output:

engine
Peter
  • 8,776
  • 6
  • 62
  • 95