Kenny
Kenny

Reputation: 2144

Regex After Last / and Before period

Sorry if the title is confusing. All I'm trying to do is some simple regex:

The text: /thing/images/info.gif

And what I want is: info

My regex (not fully working): ([^\/]+$)(.*?)(?=\.gif)

(Note: [^\/]+$ returns info.gif)

Thanks for any help!

Upvotes: 0

Views: 671

Answers (3)

ColOfAbRiX
ColOfAbRiX

Reputation: 1059

I'd say you don't need to match all the string, so you can be much more generic. If you know your string always contains a path you can just use:

preg_match( '/([^\/]+)\.\w+$/', "/thing/images/info.gif", $matches) ;
print_r( $matches );

and it will be valid for any filename, even names that contains dots like my_file.name.jpg or spaces like /thing/images/my image.gif

Demo here.

The structure is (from the end of the regex moving to the left):

  • Match before the end of the string
  • any number of characters preceded by a dot
  • any character that is not a slash (your filename, if there is a slash, there starts the directories)

Upvotes: 1

hatef
hatef

Reputation: 6199

In editors (Sublime):

Find:^(.*)(\/)(.*)(\.)(.*)$

Replace it with:\3

In PHP:

<?php

preg_match('/^(.*)(\/)(.*)(\.)(.*)$/', '/thing/images/info.gif', $match);
echo $match[3];

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78994

Not sure how much more complex the string is but this seems to work on the test string:

preg_match('![^/.]+(?=\.gif)!', '/thing/images/info.gif', $m);

Matching NOT / NOT . followed by .gif.

Upvotes: 0

Related Questions