Page 2 of 2

Re: [Solved] chopping of text

Posted: Sun May 25, 2008 6:42 pm
by Jaxolotl
Time ago I made this function, is not perfect but it's usefull.
I someone wants to comment it I'd apreciate it.

Code: Select all

#############################################
###       TEXT REDUCE
#
  //  $string         -> (string) The input string to process
  //  $limit          -> (int) The limit of characters I want to retrive
  //  $replacement    -> (string)  The replacement (like : "....continue.")
  //  $reboundary    -> (string) Which is my boundary character
  //  $force_replacement   -> (bool)  Set to true if I want to add the replacement even if the text is smaller than the limit
 
  function extract_text($string, $limit, $replacement, $boundary = " ", $force_replacement = false){
    //prevent tag distruction by brutally strip them
    $string = strip_tags($string);
    //get the result string length
    $string_length = strlen($string);
  
    //Search the end of a word after [, int offset] and set the result as limit
    if(($limit > $string_length)&&($force_replacement)){
      $limit = @strpos($string, $boundary,$string_length - 1);
      if(!$limit){
        $limit = $string_length;
      }
    }
    else{
      $limit = @strpos($string, $boundary ,$limit);
    }
  
    if($limit){
      //Use $limit to replace width ...Text
      return substr_replace($string, $replacement,$limit);
    }
    else{
      return $string;
    }
  }
 
$my_string = "Usted puede ahora enviar su currículum a nuestra página, de esta manera las Empresas podrán revisar su CV. Pero usted tendrá que esperar hasta que el diseño y codificación de las páginas de la empresa estén listos.";
 
 echo extract_text($string = $my_string, $limit = 50, $replacement = "... continúa", $boundary = " ", $force_replacement = true);
 
 
Output:
Usted puede ahora enviar su currículum a nuestra página,... continúa



By the way feyd's example is really beautyfull, I'll combine his example with mine for my personal joy, he's allways illuminating