Tuesday, May 30, 2006

Little PHP tip: to get a shorter string.

It's simple, but helpful to get the shorter string (for abstract,...)

$num_words=10; // No. of words to get
$i=0;
$array=explode(" ",$longString);
$new_array=array();
$total=count($array);
while (($i<$num_words) && ($i<$total))
{
$new_array[]=$array[$i];
$i++;
}
$shortString = implode(" ",$new_array);

You can then make a function for reusing.

function shortString($longString,$num_words)
{
$i=0;
$array=explode(" ",$longString);
$new_array=array();
$total=count($array);
while (($i<$num_words) && ($i<$total))
{
$new_array[]=$array[$i];
$i++;
}
return implode(" ",$new_array);
}
Cheer!