Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP RegEx with or without trailing slashes

My goal:

To capture the last part of a URL whether there is or isn't a trailing slash, without the trailing slash being a part of the string on a URL similar to the one following:

http://foo.com/p/dPWjiVtX-C/
                 ^^^^^^^^^^
               The string I want

My issue:

Every way I try only allows for a trailing slash and not for a url without a trailing slash or makes the trailing slash be contained in the string I want.

What have I tried?

1. I have tried to add a slash to the end:

  $regex = "/.*?foo\.com\/p\/(.*)\//";
  if ($c=preg_match_all ($regex, $url, $matches))
  {
    $id=$matches[1][0];
    print "ID: $id \n";
  }

This results in error when I don't have a trailing slash.

2. I have tried to add a question mark:

  $regex = "/.*?foo\.com\/p\/(.*)[\/]?/";

This results in the slash, if exists, being inside my string.

My question/tl;dr:

How can I build a RegEx to not require a slash, yet keep the slash out of my preceding string?

like image 246
grepsedawk Avatar asked Dec 11 '22 12:12

grepsedawk


1 Answers

Your .* is greedy by default, so if it can "eat" the slash in the capturing group, it will.

To make it not greedy, you need .*? in the place of the .* in your capturing group. So, your regex will be:

$regex = "/^.*?instagram\.com\/p\/(.*?)[\/]?$/";
like image 100
vroomfondel Avatar answered Dec 23 '22 18:12

vroomfondel