I have the following string in a variable.
Stack Overflow is as frictionless and painless to use as we could make it.
I want to fetch first 28 characters from the above line, so normally if I use substr then it will give me Stack Overflow is as frictio
this output but I want output as:
Stack Overflow is as...
Is there any pre-made function in PHP to do so, Or please provide me code for this in PHP?
Edited:
I want total 28 characters from the string without breaking a word, if it will return me few less characters than 28 without breaking a word, that's fine.
Using the substring() Method We'll also use the lastIndexOf() method from the String class. It accepts a substring and returns the index within this string of the last occurrence of the specified substring.
The length of the string can be limited in PHP using various in-built functions, wherein the string character count can be restricted. Approach 1 (Using for loop): The str_split() function can be used to convert the specified string into the array object.
You can use the wordwrap()
function, then explode on newline and take the first part:
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';
From AlfaSky:
function addEllipsis($string, $length, $end='…')
{
if (strlen($string) > $length)
{
$length -= strlen($end);
$string = substr($string, 0, $length);
$string .= $end;
}
return $string;
}
An alternate, more featureful implementation from Elliott Brueggeman's blog:
/**
* trims text to a space then adds ellipses if desired
* @param string $input text to trim
* @param int $length in characters to trim to
* @param bool $ellipses if ellipses (...) are to be added
* @param bool $strip_html if html tags are to be stripped
* @return string
*/
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
$trimmed_text = substr($input, 0, $last_space);
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
(Google search: "php trim ellipses")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With