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.
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}
This function splits the string into words and then joins them back together again one by one. The good thing is that if there is a word that would make the string longer than the required number of characters it doesn't include the word. The function can be called like this.
echo substrwords($string,30);
This produces the following output.
This string is too long and...
Comments
Save a bit of processor time by doing this:
$length = 0; while ($length
Thanks for this, it saved my skin
Great.! - Still working, tested with PHP7.2
// UTF8 compatibility » add "mb_" before "strlen" for UTF8 compatibility
function substrwords($text, $maxchar, $end=' ...') {
if (mb_strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = mb_strlen($output)+mb_strlen($words[$i]);
if ($length > $maxchar) {
break;
}
else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
}
else {
$output = $text;
}
return $output;
}
(Y)
This is so coolaborative, then I show an more easy way:
function substrwords($text, $maxchar) {
$output = "";
$output .= substr($text, 0, $maxchar);
$output .= " ...";
return $output;
}
Maybe can validate if $text containt a string, but that is correspondence.
If a call a function is better make a condition first, like that:
if(empty($_POST['string_value_container'])) {
/* Or the process that you consider necessary, or not the process then use ! to go on else directly */
echo "Not contain an valid char/string"
}
else {
echo substrwords($string,30);
}
Thx for this little handy function.