Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this function exist in PHP?

Tags:

string

php

I found myself needing this function, and was wondering if it exists in PHP already.

/**
 * Truncates $str and returns it with $ending on the end, if $str is longer
 * than $limit characters
 *
 * @param string $str
 * @param int $length
 * @param string $ending
 * @return string
 */
function truncate_string($str, $length, $ending = "...")
{
    if (strlen($str) <= $length)
    {
        return $str;
    }
    return substr($str, 0, $length - strlen($ending)).$ending;
}

So if the limit is 40 and the string is "The quick fox jumped over the lazy brown dog", the output would be "The quick fox jumped over the lazy brow...". It seems like the sort of thing that would exist in PHP, so I was surprised when I couldn't find it.

like image 449
Jeremy DeGroot Avatar asked Mar 27 '09 15:03

Jeremy DeGroot


People also ask

How do we know if a function exists?

One way to check if a function is defined is to test it with an if statement. The trick is to test the function as a method of the window object. The code in the brackets will execute if the function is defined.

How do I know if my PHP function is working?

Determining if a PHP function is available You can determine whether or not a PHP function is enabled for your web site by using the function_exists() function.

What is an undefined function in PHP?

Code Inspection: Undefined functionReports the references to functions that are not defined in the project files, configured include paths, or among the PHP predefined functions. In the following example, the undefined_function() is not defined in the built-in library and project files.

Is callable in PHP?

The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.


1 Answers

$suffix = '...';
$maxLength = 40;

if(strlen($str) > $maxLength){
  $str = substr_replace($str, $suffix, $maxLength);
}

Your implementation may vary slightly depending on whether the suffix's length should be count towards the total string length.

like image 78
Ron DeVera Avatar answered Oct 03 '22 17:10

Ron DeVera