Dynadot

[PHP] Trim a string by length

Spaceship Spaceship
Watch
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...
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:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
0
•••
Or you can simply use:

Code:
$description = "Some example here";
echo '.substr($description, 0, 6).';

This will result in:

Code:
Some e

If you want to add some dots like "Some e...", add them in the echo.
 
0
•••
But that wouldn't work if you wanted to keep whole words.
Like vBulletin does on the last post info.
 
0
•••
Nice sample. Thumbs up for posting. Respect.

Personally i would use: strpos & strrev.

something like:

$MyStr="Hello there how are you"
to cut to 14

1. $MyStr = substr($MyStr,1,14) // "Hello there ho"
2. $MyStr=strrev($MyStr)
3. $SpacePos=strpos($MyStr,' ')
3,5. $MyStr=strrev($MyStr)
4. $MyStr=(substr($MyStr,1,(strlen($MyStr)-$SpacePos)))

(untested)
But just my 2 cents ;)
 
0
•••
Nice function Adrian, made some changes :)

PHP:
// Created by Adrian @ Cueburst.com

// Trim a string to a certain length.
// With the ability to keep whole words.

define('CHARS', 0);
define('WORDS', 1);

function str_trim($string, $method = 1, $length = 25, $pattern = '...')
{
	$truncate = $string;

	if (!is_numeric($length))
	{
		$length = 25;
	}

	if (strlen($string) <= $length)
	{
		return $truncate;
	}

	switch ($method)
	{
		case CHARS:
			$truncate = substr($string, 0, $length) . $pattern;
   			break;
		case WORDS:
			if (strstr($string, ' ') == false)
			{
				$truncate = str_trim($string, CHARS, $length, $pattern);
			}
			else
			{
				$count = 0;
				$truncated = '';

				$word = explode(' ', $string);

				foreach ($word AS $single)
				{
					if ($count >= $length)
					{
						// Do nothing...
						continue;
					}

					if (($count + strlen($single)) <= $length)
					{
						$truncated .= $single . ' ';
						$count = $count + strlen($single);
					}
					else if (($count + strlen($single)) >= $length)
					{
						break;
					}
				}
				$truncate = rtrim($truncated) . $pattern;
			}
			break;
	}
	return $truncate;
}
 
1
•••
Thanks for the comments, + that code looks much tidier SV. :)

Dotmainer, never thought of doing it that way, will consider that way in future. :tup:
 
0
•••
Updated: The function now includes spaces into the character count, and general code cleanup. :)
 
0
•••
wow thanks for this tips :tu:
 
0
•••
Nice function Adrian, made some changes :)

your algorithm is very ineffective - imagine you've got file with xx millions words and very long $length=100000, beginning from the start, cycling thru words/exploding large array is slow and resource demanding.

much faster and clean way of doing the same thing would be imho:

PHP:
<?php

function trimstr($string, $length=25, $method='WORDS', $pattern='...') {

	if (!is_numeric($length)) { 
            $length = 25; 
        } 

	if (strlen($string) =< $length) { 
            return rtrim($string) . $pattern; 
        }

	$truncate = substr($string, 0, $length); 

	if ($method != 'WORDS') { 
            return rtrim($truncate) . $pattern; 
        }

	if ($truncate[$length-1] == ' ') { 
            return rtrim($truncate) . $pattern; 
        } 
        // we got ' ' right where we want it

	$pos = strrpos($truncate, ' '); 
        // lets find nearest right ' ' in the truncated string

	if (!$pos) { return $pattern; } 
        // no ' ' (one word) or it resides at the very begining 
        // of the string so the whole string goes to the toilet

	return rtrim(substr($truncate, 0, $pos)) . $pattern; 
        // profit
}

?>





*sorry the thread is somewhat old - i didnt notice that :) anyway...
 
Last edited:
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back