Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.