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.
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.
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.
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.
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.
$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.
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