When I use substr($string,0,100)
, it gives first 100 characters. Sometimes it left the last word incomplete. That looks odd. Can I do limit by word rather than char?
Introduction to the PHP substr () function. The substr () function accepts a string and returns a substring from the string. Here’s the syntax of the substr () function: substr ( string $string , int $offset , int| null $length = null ) : string. Code language: PHP (php) In this syntax: $string is the input string.
In this example, the substr () function extract the first 3 characters from the 'PHP substring' string starting at the index 0. The following example uses the substr () function to extract a substring from the 'PHP substring' string starting from the index 4 to the end of the string: In this example, we omit the $length argument.
The last character in the input string has an index of -1. Use the negative length to omit a length number of characters in the returned substring. Use the PHP mb_substr () function to extract a substring from a string with non-ASCII characters.
Here are some examples of PHP algorithms that can be used to achieve the effect of not cutting off words into two parts while grabbing a portion of a string. $string = preg_replace ('/\s+? (\S+)?$/', '', substr ($string, 0, $length));
// Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.
if(strlen($very_long_text) > 120) {
$matches = array();
preg_match("/^(.{1,120})[\s]/i", $very_long_text, $matches);
$trimmed_text = $matches[0]. '...';
}
If you just count the words the resulting sting could still be very long as a single "word" might have 30 characters or more. I would suggest instead truncating the text to 100 characters, except if this causes a word to be truncated then you should also remove the truncated part of the word. This is covered by this related question:
How to Truncate a string in PHP to the word closest to a certain number of characters?
Using wordwrap
$your_desired_width = 100;
if (strlen($string) > $your_desired_width)
{
$string = wordwrap($string, 100);
$i = strpos($string, "\n");
if ($i) {
$string = substr($string, 0, $i);
}
}
This is a modified versions of the answer here. if the input text could be very long you can add this line before the call to wordwrap to avoid wordwrap having to parse the entire text:
$string = substr($string, 0, 101);
Using a regular expression (Source)
$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, 100));
$a = explode('|', wordwrap($string, 100, '|');
print $a[0];
Try a single line code
$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length));
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