Sunday 11 November 2012

How To Truncate Text Using PHP

You may have seen the short summary of the articles in several blogspot and wordpress blogs. What if you want it in your own CMS website?  Well, you can apply your own style of shortening or summarizing your content article by simply following the tutorial below.

We will be using substr() to truncate the specified number of texts you want to show. The substr() returns the portion of string specified by the start and length parameters.For example,
<?php
echo substr(‘ABCDEF’,1);
?>
Results BCDEF on your web browser.
The parameter 1 says to omit the first character, A. If no number parameter is given after that then it loads all the character “BCDEF”
On the other hand,
<?php
echo substr(‘ABCDEF’,1,3);
?>
results BCD on your browser screen.
The first parameter 1 refers to omit the first character,”A” in the given string. And the paratemeter 3 refers to show only 3 characters, “BCD” .
In this way we can limit the characters to load on the web browser. Hence we’ll be applying same principle to truncate the text.
Let’s say the we have a variable “$myText” which contains the texts that are needed to be truncated.
<?php $myText = ‘this is textthis is textthis is textthis is textthis is text’?>
<?php echo(substr($myText, 0,25))’…’; ?>
The above code sample will load only 25 characters (including space) from the begining.
If you try the above sample code in your browser it will give the following result:
“this is textthis is textt…”

If you are familar with few php scripts then you may also know that the external text files can be loaded in the variable “$myText” for a simple example, you can use; $string = fopen(“textfile.txt”,”r”);
You may also add, permalinks after the summary.
Hope it was helpful.

No comments:

Post a Comment