Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

How to use PHP Magic to create a string builder with append format in PHP.

0.00/5 (No votes)
7 Feb 2011CPOL 5.6K  
Here is the one i wrote sometime ago/* ---------------------------------------------------------------------------- * Teknober.com - All rights reserved * ---------------------------------------------------------------------------- * File Name : TStringBuilder.php * Section ...
Here is the one i wrote sometime ago


/* ----------------------------------------------------------------------------
 * Teknober.com - All rights reserved
 * ----------------------------------------------------------------------------
 * File Name    : TStringBuilder.php
 * Section      : TStringBuilder
 * Dependicies  : none
 * Description  : Implements TStringBuilder class
 * ----------------------------------------------------------------------------
 * Author       : Fatih P
 * E-mail       : v-fpiris@     .com [removed to avoid spam]
 * ----------------------------------------------------------------------------
 * $LastChangedRevision: 38 $
 * --------------------------------------------------------------------------*/
class TStringBuilder {
    private $str = null;

    /**
     * Initializes a new instance
     */
    public function __construct()
    {
        $this->str = array();
    }

    /**
     * Adds new string
     * @param string $str
     */
    public function add($str)
    {
        $this->str[] = $str;
    }

    /**
     * Clears the string
     */
    public function clear() {
        $this->str = array();
    }

    /**
     * Gets internal array
     */
    public function get() {
        $this->str;
    }

    /**
     * Dumps string
     * @param string $seperator
     * @return string
     */
    public function dump($seperator = "") {
        $retVal = "";
        foreach($this->str as $k) {
            $retVal .= $k . $seperator;
        }

        return substr($retVal, 0, strlen($retVal) - strlen($seperator));
    }

    /**
     * Get number of enteries added
     * @return int
     */
    public function count() {
        return count($this->str);
    }

    /**
     * Get string length
     * @return int
     */
    public function length() {
        $retVal = 0;
        foreach($this->str as $k) {
            $retVal += strlen($k);
        }

        return retVal;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)