NamePros
Welcome, Guest! Ready to make a name for yourself in the domain business? We welcome both the hobbyist and professional domainer to join the discussion as part of the NamePros community.

Click here to create your profile to start earning reputation for posting, and trader ratings for buying & selling in our free e-marketplace. Build your trader rating with each successful sale. Our system has tracked over 100,000 sales and counting!
FAQ & TOS Register Search Today's Posts Mark Forums Read

Go Back   NamePros.com > Website Development Discussion Forums > Programming > CODE
Reload this Page [PHP] Trim a string by length

CODE This forum is for posting code snippets and example scripts that aren't quite tutorials, but could be useful for others. You may post code snippets and/or completed scripts that you've written and want to share here.

Advanced Search
6 members in live chat ~  


Reply
 
LinkBack Thread Tools
Old 04-26-2011, 09:46 AM THREAD STARTER               #1 (permalink)
Senior Member
 
Hitch's Avatar
Join Date: Aug 2005
Location: Uk, South Yorkshire
Posts: 1,228
Hitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to behold
 


Winner
PHP Programming - May 2007
Animal Rescue Third World Education Find Marrow Donors!

[PHP] Trim a string by length


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...
Quote:
Hello, my name is Adrian Crepaz.
Trimmed to 19 Characters.
Quote:
Hello, my name is A...
Trimmed to a maximum 19 Characters, but keeping words whole.
Quote:
Hello, my name is...
PHP Code:
<?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
    {
????: NamePros.com http://www.namepros.com/code/712577-php-trim-a-string-by-length.html
        switch(
$method)
        {
            case 
CHARS:
                return 
substr($string0$length) . $pattern;    
            break;
        
            case 
WORDS:
                if (
strstr($string' ') == false
                {
                    return 
str_trim($stringCHARS$length$pattern);
                }
            
                
$count 0;
                
$truncated '';
                
$word explode(" "$string);
????: NamePros.com http://www.namepros.com/showthread.php?t=712577
                
                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 Code:
<?php
    
    $string 
"Hello, this is an example";
    
    echo 
str_trim($string);
    
// Returns trimmed string with defaults above
        
    
echo str_trim($stringCHARS43'...');
    
// With different options
    
?>
It's simple to use. Enjoy.

UPDATED: It now adds the spaces into the character count, plus cleanup.
Last edited by Hitch; 10-25-2011 at 02:52 AM.
Hitch is offline   Reply With Quote
Old 04-27-2011, 06:12 AM THREAD STARTER               #2 (permalink)
Senior Member
 
Hitch's Avatar
Join Date: Aug 2005
Location: Uk, South Yorkshire
Posts: 1,228
Hitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to behold
 


Winner
PHP Programming - May 2007
Animal Rescue Third World Education Find Marrow Donors!
Fixed a bug.
Hitch is offline   Reply With Quote
Old 04-27-2011, 06:50 AM   #3 (permalink)
NamePros Regular
 
cipcip's Avatar
Join Date: Mar 2007
Location: Constanta, Romania
Posts: 502
cipcip is just really nicecipcip is just really nicecipcip is just really nicecipcip is just really nice
 



Or you can simply use:

Code:
$description = "Some example here";
echo '.substr($description, 0, 6).';
This will result in:
????: NamePros.com http://www.namepros.com/showthread.php?t=712577

Code:
Some e
If you want to add some dots like "Some e...", add them in the echo.
__________________
Social networking aggregator
cipcip is offline   Reply With Quote
Old 04-27-2011, 07:53 AM THREAD STARTER               #4 (permalink)
Senior Member
 
Hitch's Avatar
Join Date: Aug 2005
Location: Uk, South Yorkshire
Posts: 1,228
Hitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to behold
 


Winner
PHP Programming - May 2007
Animal Rescue Third World Education Find Marrow Donors!
But that wouldn't work if you wanted to keep whole words.
Like vBulletin does on the last post info.
Hitch is offline   Reply With Quote
Old 04-27-2011, 12:03 PM   #5 (permalink)
Member
 
Dotmainer's Avatar
Join Date: Mar 2007
Posts: 1,358
Dotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud ofDotmainer has much to be proud of
 



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 ;-)
__________________
UniquePSD / YourPetCommunity...

Dotmainer is offline   Reply With Quote
Old 04-27-2011, 12:29 PM   #6 (permalink)
Tech Support
Join Date: Mar 2005
Posts: 4,944
Eric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatnessEric Has achieved greatness
 

Member of the Month
MOTM September 2005
Save a Life Child Abuse 9/11/01 :: Never Forget Baby Health Marrow Donor Program AIDS/HIV Breast Cancer Animal Rescue Cystic Fibrosis Ethan Allen Fund Animal Cruelty Ethan Allen Fund Ethan Allen Fund Baby Health Cancer Alzheimer's Protect Our Planet Cancer Survivorship SIDS Child Abuse Diabetes Protect Our Planet Multiple Sclerosis Autism Adoption Special Olympics
Nice function Adrian, made some changes

PHP Code:
// 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 '...')
????: NamePros.com http://www.namepros.com/showthread.php?t=712577
{
    
$truncate $string;

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

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

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

                
$word explode(' '$string);

                foreach (
$word AS $single)
                {
????: NamePros.com http://www.namepros.com/showthread.php?t=712577
                    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;

Eric is offline   Reply With Quote
Old 04-27-2011, 02:16 PM THREAD STARTER               #7 (permalink)
Senior Member
 
Hitch's Avatar
Join Date: Aug 2005
Location: Uk, South Yorkshire
Posts: 1,228
Hitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to behold
 


Winner
PHP Programming - May 2007
Animal Rescue Third World Education Find Marrow Donors!
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:
Hitch is offline   Reply With Quote
Old 10-25-2011, 02:54 AM THREAD STARTER               #8 (permalink)
Senior Member
 
Hitch's Avatar
Join Date: Aug 2005
Location: Uk, South Yorkshire
Posts: 1,228
Hitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to beholdHitch is a splendid one to behold
 


Winner
PHP Programming - May 2007
Animal Rescue Third World Education Find Marrow Donors!
Updated: The function now includes spaces into the character count, and general code cleanup.
Hitch is offline   Reply With Quote
Old 10-28-2011, 02:45 PM   #9 (permalink)
NamePros Member
Join Date: Jan 2011
Posts: 83
RSKK is an unknown quantity at this point
 



wow thanks for this tips
RSKK is offline   Reply With Quote
Old 02-18-2012, 09:12 AM   #10 (permalink)
4pm
NamePros Regular
 
4pm's Avatar
Join Date: Jun 2011
Location: Moscow
Posts: 622
4pm is a splendid one to behold4pm is a splendid one to behold4pm is a splendid one to behold4pm is a splendid one to behold4pm is a splendid one to behold4pm is a splendid one to behold4pm is a splendid one to behold
 



Originally Posted by Eric View Post
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 Code:
<?php

function trimstr($string$length=25$method='WORDS'$pattern='...') {
????: NamePros.com http://www.namepros.com/showthread.php?t=712577

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

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

    
$truncate substr($string0$length); 

    if (
$method != 'WORDS') { 
????: NamePros.com http://www.namepros.com/showthread.php?t=712577
            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($truncate0$pos)) . $pattern
        
// profit
}

?>




*sorry the thread is somewhat old - i didnt notice that anyway...
__________________
Webbox | 1st.ly | PR checker
Last edited by 4pm; 02-19-2012 at 12:00 PM.
4pm is offline   Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools


Similar Threads
Thread Thread Starter Forum Replies Last Post
PHP Fuction - Parse a String + Extras MJ Web Development Wanted 2 11-17-2008 09:56 AM
SEO and URL 2 (domain name part of search string?) interestedenough Search Engines 2 04-02-2008 09:40 AM
encrypt and decrypt query string sales@vannova.com Programming 5 06-06-2007 11:45 PM
Alternating string splits Outer Programming 1 08-11-2005 03:05 AM
What length is your domain? jaikini Domain Name Discussion 16 07-18-2004 07:32 AM

 
All times are GMT -7. The time now is 07:40 PM.

Domain name forum recommended by Domaining.com Powered by: vBulletin® Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.6.0 Ad Management plugin by RedTyger