How to trim recursively in PHP

April 28th, 2011 by usage | Filed under PHP, Programming

How to recursively trim in PHP

<?php

// Usage:

echo Our_Util_String::trim('test');

/**
 * Util string functions.
 *
 * @author Svetoslav Marinov <svetoslavm@gmail.com>
 * @copyright Svetoslav Marinov <svetoslavm@gmail.com> & others
 * @version 1.0
 */
class Our_Util_String {
    /**
     * Recursive Trimmer :)
     * http://php.net/manual/en/function.trim.php
     *
     * @param mixed $arr
     * @param string $charlist
     * @return mixed
     */
    function trim($arr, $charlist = ' ') {
        if (is_string($arr)) {
            return trim($arr, $charlist);
        } elseif (is_array($arr)) {
            foreach($arr as $key => $value){
                if (is_array($value)) {
                    $result[$key] = self::trim($value, $charlist);
                } else {
                    $result[$key] = trim($value, $charlist);
                }
            }

            return $result;
        } else {
            return $arr;
        }
    }
}

?>

tag_icon

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a comment.

To leave a comment, please fill in the fields below.