PHPEdit.net Community
   
1 2 3 4
Tutorials Tips Pasties Code Snippets
 

Home > Code snippets > PHP > Files > Get first line

Get first line

Created by axiac, last update on 26/02/2008 17:32

Truncate a given multi-line string by returning only a limited length substring from its first line. Add suspension points or other (provided) continuation mark if the string is truncated in-process; the input string is returned as-is if it does not contain new-line characters and its length is smaller than required.

  1. function ltGetFirstLine($text, $maxChars = 0, $cont = '...')
  2. {
  3. // Verify parameters
  4. $maxChars = max(0, intval($maxChars));
  5. if ($maxChars > 0)
  6. $cont = substr($cont, 0, $maxChars);
  7.  
  8. // If the text has more than one line then keep the first one
  9. // and replace the rest with continuation fragment
  10. $text = preg_replace('/[\r\n].*$/s', $cont, $text, 1);
  11.  
  12. // Keep only the required amount of characters (if specified)
  13. // and append continuation if needed
  14. if ($maxChars > 0 && strlen($text) > $maxChars)
  15. return substr($text, 0, $maxChars - strlen($cont)) . $cont;
  16. else
  17. return $text;
  18. }

Dependencies

No special requirements are needed by this snippet

By logging in you will be able to:

  • Recommand this page to someone else
  • Monitor changes on this item
  • Rate this item
  • Post comments
  • Download this item
Login now!

 
PHPEdit User Community, © 2008 WaterProof SARL
Powered by PHPEdit