Skip to content

Instantly share code, notes, and snippets.

@katienelson
Created July 24, 2014 16:24
Show Gist options
  • Save katienelson/89514f12c3922dbce0ff to your computer and use it in GitHub Desktop.
Save katienelson/89514f12c3922dbce0ff to your computer and use it in GitHub Desktop.
String Limiter - Limit a string to a maximum length of $limit and append '...' before returning value. Originally written as a ModX snippet
<?php
/**
* Limit a string to a maximum length of $limit and append ... before returning
* Default Limit: 30
*/
if(!isset($string)){ return; }
if(!isset($limit)){ $limit = 30; }
if(strlen($string) > $limit){ // if the string is too long
$substr = substr($string, 0, $limit); // shrink the string
$strlast = $substr[strlen($substr) -1]; // get the last character in the string
if($strlast == ' '){ $substr = substr($substr, 0, -1); } // if last char is a space, trim it off
return $substr . '...'; // append ...
}
return $string; // return original string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment