CodeCrack
CodeCrack

Reputation: 5373

Extracting content between last 2 slashes with pregex

I have urls such as

/blah/WHATEVER/sites/two/one/blah/need/this.ini

in PHP, how do I extract /need/this.ini with regular expressions?

Upvotes: 0

Views: 949

Answers (3)

Andrew D.
Andrew D.

Reputation: 1022

Notice # instead of /

if (preg_match('#/?[^/]+?/?[^/]+$#', $path, $m) !== false) {
  // $m[0]` will contain the desired part
} 

But there is better way to do this - don't use regexp at all:

function extract_part($path) {
  $pos = strrpos( $path, '/');
  if ($pos > 0) { // try to find the second one
    $npath = substr($path, 0, $pos-1);
    $npos = strrpos($npath, '/');
    if ($npos !== false) {
      return substr($path, $npos);
    } 
    // This is not error, uncomment to change code behaviour.
    /*else { // Returns '/this.ini' in your case
      return substr($path, $pos);
    }*/
  }

  // Returns as is
  return $path;
}

(I have no php interpreter under my hands, so the code is not checked). Yep, there was an error :) and now its fixed.

Upvotes: 0

Damien Pirsy
Damien Pirsy

Reputation: 25445

Without:

$url = '/blah/WHATEVER/sites/two/one/blah/need/this.ini';
$array = explode('/',$url);
$rev = array_reverse($array);
$last = $rev[0];
$second_last = $rev[1];
// or $rev[1].'/'.$rev[0]

A bit longer, I'm sure there are even better and clearer ways than this. Anyway, just to say you don't need regexes for this kind of stuff. Regexes are not a solution for everything :)

If you don't need the array intact, you can also array_pop() twice, and each time you get the last element. But you will shorten the array by one element each time.

Also:

    $url = '/blah/WHATEVER/sites/two/one/blah/need/this.ini';
    $array = explode('/',$url);
    $last = end($array);
    $second_last = prev($array);

See it in action

Upvotes: 3

Regexident
Regexident

Reputation: 29552

This should do:

(/[^/]+/[^/]+)$

(does not check for escaped slashes though.)

Upvotes: 0

Related Questions