Word Sensative substr function


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3. * word-sensitive substring function with html tags awareness
  4. * @param text The text to cut
  5. * @param len The maximum length of the cut string
  6. * @returns string
  7. **/
  8. function substrws( $text, $len=180 ) {
  9.  
  10. if( (strlen($text) > $len) ) {
  11.  
  12. $whitespaceposition = strpos($text," ",$len)-1;
  13.  
  14. if( $whitespaceposition > 0 )
  15. $text = substr($text, 0, ($whitespaceposition+1));
  16.  
  17. // close unclosed html tags
  18. if( preg_match_all("|<([a-zA-Z]+)>|",$text,$aBuffer) ) {
  19.  
  20. if( !empty($aBuffer[1]) ) {
  21.  
  22. preg_match_all("|</([a-zA-Z]+)>|",$text,$aBuffer2);
  23.  
  24. if( count($aBuffer[1]) != count($aBuffer2[1]) ) {
  25.  
  26. foreach( $aBuffer[1] as $index => $tag ) {
  27.  
  28. if( empty($aBuffer2[1][$index]) || $aBuffer2[1][$index] != $tag)
  29. $text .= '</'.$tag.'>';
  30. }
  31. }
  32. }
  33. }
  34. }
  35.  
  36. return $text;
  37. }
  38. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.