el_pup_le
el_pup_le

Reputation: 12179

Get filename from filepath string and remove unwanted trailing characters

I would like to capture the last folder in paths without the year. For this string path I would need just Millers Crossing not Movies\Millers Crossing which is what my current regex captures.

G:\Movies\Millers Crossing [1990]

preg_match('/\\\\(.*)\[\d{4}\]$/i', $this->parentDirPath, $title);

Upvotes: 3

Views: 141

Answers (4)

Felix Kling
Felix Kling

Reputation: 816442

How about basename [docs] and substr [docs] instead of complicated expressions?

$title = substr(basename($this->parentDirPath), 0, -6);

This assumes that there will always be a year in the format [xxxx] at the end of the string.

(And it works on *nix too ;))

Update: You can still use basename to get the folder and then apply a regular expression:

$folder = basename($this->parentDirPath);
preg_match('#^(.*?)(?:\[\d{4}\])?$#', $str, $match);
$title = $match[1];

Upvotes: 5

Brad Christie
Brad Christie

Reputation: 101604

Simpler approach:

([^\\]*)\s?\[\d{4}\]$

I believe your issue is also with you including "double backslashes" (e.g. \\\\ instead of a single \\. You can also make life easier by using a class to include characters you don't want by prefixing it with a caret (^).

Upvotes: 0

Justin Morgan
Justin Morgan

Reputation: 30760

It looks like you want something like this:

/([^\\])+\s\[\d{4}\]$/

That's what I'd go with, at least. Should only include whatever comes after the last backslash in the string, and the movie title will be in the first capture group.

Upvotes: 0

Håvard
Håvard

Reputation: 10080

Try

preg_match('/\\\\([^\\]*)\[\d{4}\]$/i', $this->parentDirPath, $title);

Basically, instead of matching any character with ., you're matching any character but \.

Upvotes: 1

Related Questions