Regular Expressions 101

Community Patterns

Catch full string up until last backslash

0

Regular Expression
PCRE (PHP <7.3)

Description

Anything before the final \ will be detected. In the example below, the files will be stripped from the file-path as the regex will detect anything in the filepath up until the final backslash.

setup In the root of your project you save the script below in index.php and should create folder named app. To see the effect of the script, you should add additional folders and files to the app folder and any folders you may create.

$path = 'app';

$dir  = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);

$pattern = '/.*[\\\\]/'; 
$replacement = '';

foreach ($files as $file) {	
    $oldfile = $file;
		$newfile = preg_replace($pattern, $replacement, $file);

		echo $oldfile . '<br>'; // verify the old setup is active
		echo $newfile . '<br>'; // updated only to show file and end directory

		preg_match_all($pattern, $file, $matches, PREG_SET_ORDER, 0);
		var_dump($matches);
}
Submitted by anonymous - 5 years ago