Julian Lannigan

PHP String Padding { 0 }

I recently wrote a small function that will limit and pad a string all in one.  I used it specifically when doing some programming through the CLI interface.  Definitely helped when formatting “tables” in the console.  Without further ado:

function strpadding($str, $maxlen = 30, $padlen = 5, $padchr = " ") {
    $str = trim($str);
    if (strlen($str) <= $maxlen) {
        return str_pad($str, $maxlen+$padlen, $padchr);
    } else {
        return str_pad(substr($str, 0, $maxlen), $maxlen+$padlen, $padchr);
    }
}

The only real downside to the above function is that it will just snip the passed string without a real notification. Here is a function that will add “…” to the end of the string if it is longer than the given max length.

function strpadding($str, $maxlen = 30, $padlen = 5, $padchr = " ") {
    $str = trim($str);
    if (strlen($str) <= $maxlen) {
        return str_pad($str, $maxlen+$padlen, $padchr);
    } else {
        return str_pad(substr($str, 0, $maxlen-3)."...", $maxlen+$padlen, $padchr);
    }
}

Then, if you what to make the “…” editable and not forced, here is a function that makes it a parameter.

function strpadding($str, $maxlen = 30, $padlen = 5, $padchr = " ", $snipstr = "") {
    $str = trim($str);
    if (strlen($str) <= $maxlen) {
        return str_pad($str, $maxlen+$padlen, $padchr);
    } else {
        if ($snipstr == "") {
            return str_pad(substr($str, 0, $maxlen), $maxlen+$padlen, $padchr);
        } else {
            return str_pad(substr($str, 0, $maxlen-strlen($snipstr)).$snipstr, $maxlen+$padlen, $padchr);
        }
    }
}

Enjoy! Please Comment.

Be Sociable, Share!

Leave a Reply