shortening a string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • asdfkajsdflkjsadlfkjoewqifoeiwjf@yahoo.com

    shortening a string

    Hi

    I have a string:

    $string="aslkjd aslkdiwedweodij "

    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.. :/

    Thanks!

  • Chris Hope

    #2
    Re: shortening a string

    asdfkajsdflkjsa dlfkjoewqifoeiw jf@yahoo.com wrote:
    [color=blue]
    > I have a string:
    >
    > $string="aslkjd aslkdiwedweodij "
    >
    > 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.. :/[/color]

    How about something like:

    if(strlen($stri ng) > 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/

    Comment

    • Ronald Chaplin

      #3
      Re: shortening a string

      asdfkajsdflkjsa dlfkjoewqifoeiw jf@yahoo.com wrote:
      [color=blue]
      > How can this be done in php? I know how to do it in Perl through reg
      > exp.. :/[/color]

      You can use reg expressions in PHP as well :)


      This uses Perl style expression matching

      HTH

      Ron Chaplin

      Comment

      • asdfkajsdflkjsadlfkjoewqifoeiwjf@yahoo.com

        #4
        Re: shortening a string

        Thanks guys! Works brilliantly

        Comment

        Working...