Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Text, PHP

Tags:

text

php

short

I got this function:

function shorter($text, $chars_limit) {
  if (strlen($text) > $chars_limit) 
    return substr($text, 0, strrpos(substr($text, 0, $chars_limit), " ")).'...';
  else return $text;
}

and if I use echo shorter($input, 11) it works ok, but if there are some white spaces in the input, otherwise for the input looking like:

wwwwwwwwwww

The function will change this into:

... (3 dots).

I wan't it to be changed into something like this:

www ...

Have you got any ideas how to rebuild this script? Thank you in advance.

like image 926
Lucas Avatar asked Sep 08 '11 12:09

Lucas


People also ask

How do I shorten text in PHP?

You can specify the following variables: $text – The text string that you want to shorten. $max – The maximum number of characters allowed (default = 50) $append – The appended text (default = ellipses)

How do I limit text in PHP?

This is what I use: // strip tags to avoid breaking any html $string = strip_tags($string); if (strlen($string) > 500) { // truncate string $stringCut = substr($string, 0, 500); $endPoint = strrpos($stringCut, ' '); //if the string doesn't contain any space then it will cut without word basis.

What is substring in PHP?

The substr() is a built-in function of PHP, which is used to extract a part of a string. The substr() function returns a part of a string specified by the start and length parameter. PHP 4 and above versions support this function.

How do I cut a string after a specific character in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.


1 Answers

Im assuming you just want to take an input. If it is longer than X then cut it off at X and add "...".

// Start function
function shorter($text, $chars_limit)
{
    // Check if length is larger than the character limit
    if (strlen($text) > $chars_limit)
    {
        // If so, cut the string at the character limit
        $new_text = substr($text, 0, $chars_limit);
        // Trim off white space
        $new_text = trim($new_text);
        // Add at end of text ...
        return $new_text . "...";
    }
    // If not just return the text as is
    else
    {
    return $text;
    }
}

I didn't test this, but it should work. :)

like image 98
Adam Avatar answered Sep 21 '22 02:09

Adam