Remove x characters from the middle of a string.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    Remove x characters from the middle of a string.

    I'm stuck on a little bit of logic.

    Imagine, if a string's length, l, exceeds some specified maximum length, m. How could you then remove the correct amount of characters from the center of the string (replace with ellipsis: ...) so that it is less than or equal to the maximum length.

    m = 20
    string = averylongstring over20chars

    would become: averylongs...ve r20chars

    I'm befuddled on this one.
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    I wrote this 2-3 years ago that did similar to what you are asking (I think)
    Not making any great claims on how it works but maybe will help you.
    I used it as part of a search engine.
    I think BLOCK is a constant int.
    highlight() is another function that colours matching terms red
    Code:
    function parseText($text,$findme)
    {
        $textArray = preg_split ('/ /', $text );
        $words = sizeof($textArray);
        
        $side = (int)(BLOCK/2);
        $line = '';
    
        for($key=0;$key<$words;$key++)
        {
            if($key<$side)
                $start = 0;
            else
                $start = $key-$side;
            if(($start+BLOCK)>$words)
                $start = $words-BLOCK;
    
            $pos = stripos($textArray[$key], $findme);
            if ($pos !== false)
            {
                $chunk =  array_slice ($textArray,$start,BLOCK);
                $chunk = implode($chunk,' ');
    
                //Add Ellipses
                if($start>0)
                    $line .= '.....';
               if($words>($start+BLOCK))
                    $chunk .= '.....';
                $line .= $chunk;
                $line .= '<br>';
            }
        }//for
        if($line!='')
            $display = highlight($line,$findme);
        //No matches found so just truncate text
        else
        {
            $chunk =  array_slice ($textArray,0,BLOCK);
            $display = implode($chunk,' ');
            $display .= '.....';
        }
        return $display;
    }

    Comment

    Working...