Trying to get the file path in php7:

$keywords = preg_split("/[\\,]+/", dirname($filename)); 

How to get the last element if a string:

 upload/iblock/faa/file.jpg 
  • last element is faa ? that is, you pass it to a function without a file name. - teran
  • Yes, I give dirname ($ filename) - Basil Jimmy
  • one
    pathinfo , basename . - user207618
  • And we need to get the last element of the path - Basil Jimmy
  • What is meant by the last element? In general, to work with file paths there is pathinfo php.net/manual/ru/function.pathinfo.php - Mikhail Kovalev

1 answer 1

To get the last section of path strings using regular expressions, you can use, for example, the following option: ([\w\s]+)\/?$ . The last slash is optional. The characters A-Za-z0-9_ and a space fall into \w\s . You can add by adding there, for example, А-Яа-я- , etc.

 preg_match("/([\w\s]+)\/?$/", "/upload/iblock/faa/", $matches); print_r($matches); 

In the first group there will be the required line:

 Array ( [0] => faa/ [1] => faa ) 

In general, knowing the dirname() function that you use in your code, you probably also know about the basename() function, which returns the last element of the path, as well as pathinfo() , SplFileInfo::getFilename . To get the path, you can even break it up with explode() and get the last element using array_pop . Therefore, if your task is to work with paths, and not train regular expressions, then use the appropriate functions.