Skip to content

Instantly share code, notes, and snippets.

@jrobinsonc
Last active May 3, 2018 20:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrobinsonc/5897554 to your computer and use it in GitHub Desktop.
Save jrobinsonc/5897554 to your computer and use it in GitHub Desktop.
Cut/truncate text to specific length. #php #strings

Cut text to specific length

Use this function to cutting text to a specific length, with the ability to prevent that the last word be cutted in half.

Usage

require 'cutText.php';

$text1 = 'Lorem ipsum dolor sit amet, sed do eiusmod tempor incididunt ut laboredo.';

// Normal usage:
printf('%s<br>', cutText($text1, 20));

// Using an space for break the string:
printf('%s<br>', cutText($text1, 20, ' '));
<?php
/**
* Cut text to specific length.
*
* @author JoseRobinson.com
* @version 201306301956
* @link GitHup: https://gist.github.com/5897554
* @param string $str The text to cut.
* @param int $limit The maximum number of characters that must be returned.
* @param stirng $brChar The character to use for breaking the string.
* @param string $pad The string to use at the end of the cutted string.
* @return string
*/
function cutText($str, $limit, $brChar = ' ', $pad = '...')
{
if (empty($str) || strlen($str) <= $limit) {
return $str;
}
$output = substr($str, 0, ($limit+1));
$brCharPos = strrpos($output, $brChar);
$output = substr($output, 0, $brCharPos);
$output = preg_replace('#\W+$#', '', $output);
$output .= $pad;
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment