Alan Hogan

Feed
  
Written: Fri., July 21st, 2006 

PHP function chopOffLastDir()

I wrote this funtion to help avoid 404 errors when a user asks for something like /my/site/section/doesntexist/. I use it to help bump users “up” to /my/site/section/. Feel free to use/modify/share it; I’m making it public domain.

<?php
/* chopOffLastDir v1.2
   by Alan Hogan (alan.pixelsandpages.com)
   This function, formerly known as allButLastBit,
   is meant to chop off the last directory in a GET request.
   Ex: chopOffLastDir("/about/website/php/")
   returns "/about/website/"
   Note: Accepts dirs in any of the following
   forms (not including quotes):
   "a/b/c"
   "/a/b/c/"
   "a/b/c/"
   "/a/b/c"
   However, it will always return this:
   "/a/b/" 
*/

function chopOffLastDir($string,$separator='/')
{
  if ($string[0]!=$separator)
  {
    $string=$separator.$string;
  }
  if (substr($string,-1)!=$separator)
  {
    $string.=$separator;
  }
  $exploded = explode($separator,$string); 
  $numValues = count($exploded)-2;
  for($n=0;$n<$numValues;$n++)
  {
    $output.=$exploded[$n].$separator;
  }
  return $output;
}
?>

Comments

#

Note

Posted by: alanhogan

I would like to point out the basename() function of PHP has a similar purpose. However this one may be useful for very simple CMSs.

Alan J. Hogan

Commenting is not currently enabled.

Original content, graphics, and code © Alan J. Hogan 2000–2009. Contact me.

Other work © respective authors.

Site map