Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

How to clean spaces and truncate to a given length in PHP?

$
0
0

Snippet

  1. ////////////////////////////////////////////////////////////////////////////////////////////
  2. // USAGE
  3. //
  4. // [if second argument is false the word length is not truncated
  5. // [if second argument is numeric that it the max length of the returned word
  6. // examples:
  7. // $word_string = clean_spaces(' string of      words with  different number    of  spaces    ', false);
  8. // $word_string = clean_spaces(' string of      words with  different number    of  spaces    ', 3);
  9. //
  10.  
  11. function clean_spaces($words_in, $length)
  12. {
  13.      if( $length ){
  14.      $words_check = preg_replace('/\s\s+/', '', trim($words_in));
  15.      $words_len = explode('', $words_check );
  16.      foreach( $words_lenas$word => $value){
  17.           if( strlen( $value )> $length ){
  18.  
  19.      // un comment this line to show the dots of truncated words
  20.      //$word_fixed = substr( $value, 0, $length) . '…';
  21.  
  22.      $word_fixed = substr( $value, 0, $length);
  23.      $words_out = $words_out . '' . $word_fixed;
  24.           }
  25.      }
  26.  
  27. }else{
  28.      $words_out = preg_replace('/\s\s+/', '', trim($words_in));
  29. }
  30.  
  31. return$words_out;
  32.  
  33. }

<!--break-->


Viewing all articles
Browse latest Browse all 178

Trending Articles