17th April 2008 - 4 minutes read time
Cutting a string to a specified length is accomplished with the substr() function. For example, the following string variable, which we will cut to a maximum of 30 characters.
$string = 'This string is too long and will be cut short.';
The substr() function has three parameters. The first is the string, the second is where to start cutting from and the third is the amount of characters to cut to. So to cut to 30 characters we would use the following.
$string = substr($string,0,30);
The string variable is now set to the following.
This string is too long and wi
This example highlights the major problem with this function in that it will take no notice of the words in a string. The solution is to create a new function that will avoid cutting words apart when cutting a string by a number of characters.