PHP Directory name parsing thing

For any useful advice you want to share, on any subject under the sun.

Moderator: Thought Police

Thought Police
Thought Police
Posts: 1205
Joined: Thu Mar 14, 2002 12:11 pm
Location: Macclesfield

PHP Directory name parsing thing

Post by heavy-rotation »

Code: Select all

	function split_dir_name ($dir)
		$dir = explode ('/', ereg_replace ('//', '/', ereg_replace ('/$', '', $dir)));
		for ($res = array (); empty ($res) || empty ($dir), $f = array_shift ($dir); $f == ".." ? array_pop ($res) : $res[] = $f);
		return empty ($res) ? array ('.') : $res;
Just finished this particularly hideous piece of code (It did look normal before, but I decided it was using way too many lines ;)).

It takes a directory name something like this: 'pages/tutorials/php/' and gives you an array of the directory names back.

Thats not especially useful on its own (apart from doing breadcrumbs or something similar), but it also is quite handy, as it will work out the 'real' dir path when you give it things with ../ in for instance, so in goes:


and out comes ['pages', 'downloads', 'wallpapers']

It also stops paths from going 'above' the cwd - so '../' would return '.', and it stops things like 'pages/../../' working too (so people can't nose around where they're not supposed to, if you're using a dir lister or something).
World Controller
World Controller
Posts: 10412
Joined: Tue Jan 22, 2002 12:00 am
Location: Hear.

Post by Kajun »

What was the application you made from it though heavy? I can visualise it being useful in the way that most things are useful, but not in the way that things are useful.
Kajun is awaiting approval.