dexter dexter - 1 month ago 10
PHP Question

how to get foldername and filename using regex

i have output from string

foldername/subfolder/filename.jpg


how to get only
foldername/subfolder/
and only
filename.jpg


$filepath = 'foldername/subfolder/filename.jpg';

$folder= (preg_match('~[^A-Za-z0-9_\./\]~', $filepath));
echo 'folder:' .'<br>' .$folder;

$filename =(preg_match('....', $filepath));

echo 'fileneme' .'<br>' .$filename;


output

folder:
foldername/subfolder/

filename:
filename.jpg


thank you

Answer

Try this

$filepath  = 'foldername/subfolder/filename.jpg';
// using using regex
$parts = preg_split('~/(?=[^/]*$)~', $filepath );
echo " folder::".$parts[0]." AND fileneme:". $parts[1];

DEMO

Or use pathinfo

$filepath  = 'foldername/subfolder/filename.jpg';
$path_parts = pathinfo($filepath);    
echo "dirname   : ".$path_parts['dirname']."\n";
echo "basename  : ".$path_parts['basename']."\n";
echo "extension : ".$path_parts['extension']."\n";
echo "filename  : ".$path_parts['filename']."\n";

DEMO