Jump to content

regex to strip file path


DevinC

Recommended Posts

Hello, I am new to the regex and I'm hoping someone can assist me here on this:

 

Objective: create a list of files using the glob() function and use regex to strip the path, leaving only the filename.

 

i.e.

 

Array
(
    [0] => ./dump/INCOMPLETE (do not move)/PERMANENT/123549.dmp
    [1] => ./dump/INCOMPLETE (do not move)/PERMANENT/139672.dmp
    [2] => ./dump/INCOMPLETE (do not move)/PERMANENT/dummy.dmp
)

to

Array
(
    [0] => 123549.dmp
    [1] => 139672.dmp
    [2] => dummy.dmp
)

 

// File list generator without path
// Usage: string argument must terminate with a trailing forwardslash
function generateFilelistWithoutPath($path) {
$pattern = $path . "*.dmp";
$filelist = glob($pattern); // generate list of file
//	print_r($filelist);
if (!empty($filelist)) {
	//reconstruct array without path
	while (list($key, $val) = each($filelist)) {
		$val = ltrim($val, $path); // strip path
		if (!isset($filelistWithoutPath)) {
			$filelistWithoutPath = array($key => $val); // initialize
		} else {
			$filelistWithoutPath = array_merge($filelistWithoutPath, array($key => $val)); // merge to existing
		}
	}
	if (!isset($counter)) {$counter = 0;} // initialize
	for ($counter; $counter < count($filelistWithoutPath); ++$counter) {
		$file = "$filelist[$counter]";
		$fileWithoutPath = "$filelistWithoutPath[$counter]";
	}
}
return $filelistWithoutPath;
}

 

I realize that the Trim() function require $path in regex format but glob() require actual path so am I correct in thinking that I need to pass on two separate argument instead of 2-in-1? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/251346-regex-to-strip-file-path/
Share on other sites

I am not sure why you recommended basename() as it is not what I was looking for.

 

Anyway I have solved my own problem (without using regex) by replacing the line:

 

$val = ltrim($val, $path); // strip path

 

with

 

$val = str_replace($path, "", $val); // strip path

 

Thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.