PHP – strip leading slashes, strip trailing slashes

There is often a time when you need to strip the leading or trailing slashes from a string, usually a directory or url. Stripping the trailing and leading slashes is incredibly easy with PHP using the rtrim, and/or the ltrim function(s). It is so easy that I even hesitated to write this post… that was until I searched Google. Now, it seems necessary to make this post, as you can quickly find the wrong way to do it (no offense meant to author).

Without further ado, here are some examples:

Strip trailing slashes:

$dir = '/foo/bar/';
$stripped = rtrim($dir,'/');

Strip leading slashes:

$dir = '/foo/bar/';
$stripped = ltrim($dir,'/');

Strip trailing and leading slashes:

$dir = '/foo/bar/';
$stripped = trim($dir,'/');

Note: These methods will strip ALL leading and/or trailing slashes.
For example, this will produce the same results as our first example in where there is no trailing slashes at all.

$dir = '/foo/bar////////';
$stripped = rtrim($dir,'/');

~ by ityndall on April 27, 2011.

2 Responses to “PHP – strip leading slashes, strip trailing slashes”

  1. Thanks, ltrim example helped me 🙂

  2. Thanks, it worked like a charm.

Leave a Reply