- Impact
- 74
Hi, i wrote this today so though i'd share it.
Trim a string to a certain length
This function lets you trim a string to a specified length, either by character length, or by keeping whole words intact.
Example
We will be trimming this sentence...
Trimmed to 19 Characters.
Trimmed to a maximum 19 Characters, but keeping words whole.
Using the function
str_trim( string, method, length, separator)
Default Method = WORDS, Length = 25, Separator = ... as default
You only need to specify the string.
It's simple to use. Enjoy.
UPDATED: It now adds the spaces into the character count, plus cleanup.
Trim a string to a certain length
This function lets you trim a string to a specified length, either by character length, or by keeping whole words intact.
Example
We will be trimming this sentence...
Hello, my name is Adrian Crepaz.
Trimmed to 19 Characters.
Hello, my name is A...
Trimmed to a maximum 19 Characters, but keeping words whole.
Hello, my name is...
PHP:
<?php
// Created by Adrian at Cueburst.com
define('CHARS', null);
define('WORDS', null);
function str_trim($string, $method = 'WORDS', $length = 25, $pattern = '...')
{
if(!is_numeric($length))
{
$length = 25;
}
if(strlen($string) <= $length)
{
return $string;
}
else
{
switch($method)
{
case CHARS:
return substr($string, 0, $length) . $pattern;
break;
case WORDS:
if (strstr($string, ' ') == false)
{
return str_trim($string, CHARS, $length, $pattern);
}
$count = 0;
$truncated = '';
$word = explode(" ", $string);
foreach($word AS $single)
{
if($count < $length)
{
if(($count + strlen($single)) <= $length)
{
$truncated .= $single . ' ';
$count = $count + strlen($single);
$count++;
}
else if(($count + strlen($single)) >= $length)
{
break;
}
}
}
return rtrim($truncated) . $pattern;
break;
}
}
}
?>
Using the function
str_trim( string, method, length, separator)
- String - This is the string to trim
- Method - WORDS / CHARS - This lets you choose how to trim, by characters (string length), or maximum length (keeping whole words)
- Length - How maximum length of the string
- Separator - How to trim a sentence, usually ...
Default Method = WORDS, Length = 25, Separator = ... as default
You only need to specify the string.
PHP:
<?php
$string = "Hello, this is an example";
echo str_trim($string);
// Returns trimmed string with defaults above
echo str_trim($string, CHARS, 43, '...');
// With different options
?>
It's simple to use. Enjoy.
UPDATED: It now adds the spaces into the character count, plus cleanup.
Last edited: