Shortening text to specific characters

Shortening text to specific characters

In web pages, in some places we required to display the text according to page size. To do this, we can use a function to shorten / truncate a string of text into a specific number of characters and add three dots (…) to the end. This will also round the text to the nearest whole word instead of cutting off part way through a word.

Example

<?php

/**
* Add this to your page:
* <?php
* include “shorten_a_text_string.php”;
* echo ShortenText($text);
* ?>
* where $text is the text you want to shorten.
*
* Example
* Test it using this in a PHP page:
* <?php
* include “shortentext.php”;
* $text = “This is the text which will display 20 characters.”;
* echo ShortenText($text);
* ?>
*/

function ShortenText($text) {

//Here we can specify the number of characters to display
$chars = 20;

$text = $text.” “;
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,’ ‘));
$text = $text.”…”;

return $text;

}

?>

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.