Skip to content

Instantly share code, notes, and snippets.

@mdrakibhossainhawlader
Forked from sepehr/truncate.php
Created July 9, 2018 00:55
Show Gist options
  • Save mdrakibhossainhawlader/f3825cd372b5ce3d77a7ffebb4be4f1e to your computer and use it in GitHub Desktop.
Save mdrakibhossainhawlader/f3825cd372b5ce3d77a7ffebb4be4f1e to your computer and use it in GitHub Desktop.

Revisions

  1. @sepehr sepehr revised this gist Aug 27, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion truncate.php
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@
    * Truncates string to the specified length.
    *
    * @param string $string String to truncate.
    * @param integer $len Desired length.
    * @param integer $len Desired length.
    * @param boolean $wordsafe Whether to truncate on word boundries or not.
    * @param boolean $dots Whether to add dots or not.
    *
  2. @sepehr sepehr created this gist Aug 27, 2013.
    46 changes: 46 additions & 0 deletions truncate.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    <?php

    /**
    * Truncates string to the specified length.
    *
    * @param string $string String to truncate.
    * @param integer $len Desired length.
    * @param boolean $wordsafe Whether to truncate on word boundries or not.
    * @param boolean $dots Whether to add dots or not.
    *
    * @return string
    */
    function truncate($string, $len, $wordsafe = TRUE, $dots = TRUE)
    {
    if (mb_strlen($string) <= $len)
    {
    return $string;
    }

    $dots AND $len -= 4;

    if ($wordsafe)
    {
    // Leave one more character
    $string = mb_substr($string, 0, $len + 1);

    // Space exists AND is not on position 0
    if ($last_space = strrpos($string, ' '))
    {
    $string = substr($string, 0, $last_space);
    }
    else
    {
    $string = mb_substr($string, 0, $len);
    }
    }
    else
    {
    $string = mb_substr($string, 0, $len);
    }

    // Add ellipsis
    $dots AND $string .= ' ...';

    return $string;
    }