Posted By

skywalker on 05/15/08


Tagged

text function limit


Versions (?)

Limited Text Function - PHP


 / Published in: PHP
 

Another way of showing long text to end user...

  1. A function to limit text
  2. Of course you can also copy this code and use it freely in the scripts that you may write.
  3.  
  4. php:
  5.  
  6.  
  7. <?php
  8. function limit_text( $text, $limit )
  9. {
  10. // figure out the total length of the string
  11. if( strlen($text)>$limit )
  12. {
  13. # cut the text
  14. $text = substr( $text,0,$limit );
  15. # lose any incomplete word at the end
  16. $text = substr( $text,0,-(strlen(strrchr($text,' '))) );
  17. }
  18. // return the processed string
  19. return $text;
  20. }
  21. ?>
  22.  
  23. How do I use this function?
  24. Now to use it, you'll just have to paste the function above, into your script or onto a 'includes' file (containing all your functions) if you prefer.
  25.  
  26. Let's assume you want to paste it with your script - so, this is what you could do:
  27.  
  28. php:
  29.  
  30.  
  31. <?php
  32.  
  33. // Filename: test.php
  34. // ==================
  35.  
  36. // Our sample text
  37. $long = 'Offers a discussion board, news portal, '
  38. .'web-related articles, tutorials, scripts,'
  39. .' tech blog, photo gallery, oekaki drawing,'
  40. .' fun games, and more.';
  41.  
  42. // we only want the text to be 15 characters long.
  43. $short15 = limit_text( $long,15 );
  44. // perhaps we need one with just 6 characters.
  45. $short06 = limit_text( $long,6 );
  46.  
  47. // we output some text
  48. echo "<p>$long</p>\n";
  49. echo "<p>$short15</p>\n";
  50. echo "<p>$short06</p>\n";
  51.  
  52. // ============================================
  53. // now we paste our LIMIT_TEXT() function below
  54. // ============================================
  55.  
  56. function limit_text( $text, $limit )
  57. {
  58. if( strlen($text)>$limit )
  59. {
  60. $text = substr( $text,0,$limit );
  61. $text = substr( $text,0,-(strlen(strrchr($text,' '))) );
  62. }
  63. return $text;
  64. }
  65. ?>

Report this snippet  

You need to login to post a comment.