Skip to content

Instantly share code, notes, and snippets.

@imam932
Last active November 10, 2020 17:00
Show Gist options
  • Save imam932/e62f4d66dec8250c8070802ef718829d to your computer and use it in GitHub Desktop.
Save imam932/e62f4d66dec8250c8070802ef718829d to your computer and use it in GitHub Desktop.
cut string with spesified length
text = 'this is text'
text.substring(0, 7) + '...'
// output
// this is...
<?php
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;
}
// uses
echo substrwords($string,30);
// output
// This string is too long and...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment