Re: shortening a string

From: Chris Hope (blackhole_at_electrictoolbox.com)
Date: 01/10/05


Date: Mon, 10 Jan 2005 13:43:51 +1300

asdfkajsdflkjsadlfkjoewqifoeiwjf@yahoo.com wrote:

> I have a string:
>
> $string="aslkjdaslkdiwedweodij"
>
> When printing it out, I want it to be limited to 10 characters
> followed by "..."
>
> Result:
>
> "asjdksledo..."
>
> I only want this to happen when the string is longer than 10
> characters.
>
> How can this be done in php? I know how to do it in Perl through reg
> exp.. :/

How about something like:

if(strlen($string) > 10) {
 print substr($string, 0, 10) . '...';
}
else {
 print $string;
}

It could also be done on one line like so:

strlen($string) > 10 ? print substr($string, 0, 10) . '...' : print
$string;

-- 
Chris Hope - The Electric Toolbox - http://www.electrictoolbox.com/


Relevant Pages

  • Re: Prothon should not borrow Python strings!
    ... """It does not make sense to have a string without knowing what encoding ... same cul de sac as Python. ... Prothon_String_As_ASCII // raises error if there are high characters ... Python's split between byte strings and Unicode strings is ...
    (comp.lang.python)
  • Re: printing variable problems
    ... Marco van de Voort said ... printing a string that is prefixed with a given number of space ... characters, does not always start at the same position? ...
    (comp.lang.pascal.borland)
  • Re: Letter to US Sen. Byron Dorgan re unpaid overtime
    ... put them in stupid places. ... Programming is difficult (as you must surely appreciate, ... > strings will be in the range 1...1000 characters. ... impose an artificially small limit on string length." ...
    (comp.programming)
  • Re: Byte Array to String
    ... retrieved text will mismatch the original characters. ... encoding the characters. ... Dim strFileData as String ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: A note on personal corruption as a result of using C
    ... impossible to write effective string validation routines by definition ... (Note that a string literal may contain embedded null characters; ... without resorting to abusive language. ... In practice, programmers typically use "struct" ...
    (comp.programming)