Friday, March 19, 2010

Truncate text using php

[sourcecode language="php"]
<?php
function truncate($string, $length='' , $k = ''){
if( $length == '') $length = 50;
if( $k == '') $k = '...';
settype($string, 'string');
settype($length, 'integer');
for($a = 0; $a < $length AND $a < strlen($string); $a++){
$output .= $string[$a];
}
if( strlen($string) > $length)
$output .= $k;
return($output);
}
?>
[/sourcecode]
truncate text using php


$my_string = 'I am kajal Mondol.I live in Kolkata.';
echo truncate($my_string);
echo truncate($my_string,10);
echo truncate($my_string,10,',,,');

This will output:

I am kajal Mondol.I live in Kolkata.
I am kajal...
I am kajal,,,

This function truncates a variable to a character length, default is 50.
'...' is the default text to append if truncation occurs.
Second parameter determines how many characters to truncate to.

1 comment:

sourav said...

good job.