Breaking News
Home / Web / PHP / PHP Snippets / How to clean spaces and truncate to a given length in PHP?

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

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(‘/ss+/’, ‘ ‘, 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(‘/ss+/’, ‘ ‘, trim($words_in));
  29. }
  30.  
  31. return$words_out;
  32.  
  33. }

<!>

[pb_builder]

Check Also

How to list files in a directory in PHP?

<?php if ($handle = opendir(‘/path/to/directory’)) {     echo "Directory handle: $handlen";     echo …

Advertisment ad adsense adlogger