Search code examples
phppathsubstringtext-extraction

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);

Solution

  • 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];