Practical Web Programming

Wednesday, January 21, 2009

How to Truncate Text in PHP

Here's a simple tutorial on how to truncate text in PHP. In this tutorial, I'll be using the substr function. See the sourcecode below.

<?php

$text = 'The quick brown fox jumps over the lazy dog';
$truncated1 = substr($text, 0, 20);
$truncated2 = substr($text, 20, 40);

print "<br/>The original text: ". $text;
print "<br/>The truncated text 1: ". $truncated1;
print "<br/>The truncated text 2: ". $truncated2;

?>


Using the substr function, you can truncate a text to whatever length you want by changing the third parameter and also change the start position by changing the second parameter.

The above PHP script will output the following:

The original text: The quick brown fox jumps over the lazy dog
The truncated text 1: The quick brown fox
The truncated text 2: jumps over the lazy dog

0 comments:

Recent Post