Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 212
el_pup_le Avatar asked Nov 29 '25 23:11

el_pup_le


1 Answers

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];
like image 111
Felix Kling Avatar answered Dec 02 '25 12:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!