Posted By

luman on 09/01/06


Tagged

substr String


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

meth


strMiddleReduceWordSensitive


 / Published in: PHP
 

URL: http://es.php.net/manual/es/function.substr.php#63230

If you want to substring the middle of a string with another and keep the words intact:

  1. function strMiddleReduceWordSensitive ($string, $max = 50, $rep = '[...]') {
  2. $strlen = strlen($string);
  3.  
  4. if ($strlen <= $max)
  5. return $string;
  6.  
  7. $lengthtokeep = $max - strlen($rep);
  8. $start = 0;
  9. $end = 0;
  10.  
  11. if (($lengthtokeep % 2) == 0) {
  12. $start = $lengthtokeep / 2;
  13. $end = $start;
  14. } else {
  15. $start = intval($lengthtokeep / 2);
  16. $end = $start + 1;
  17. }
  18.  
  19. $i = $start;
  20. $tmp_string = $string;
  21. while ($i < $strlen) {
  22. if ($tmp_string[$i] == ' ') {
  23. $tmp_string = substr($tmp_string, 0, $i) . $rep;
  24. $return = $tmp_string;
  25. }
  26. $i++;
  27. }
  28.  
  29. $i = $end;
  30. $tmp_string = strrev ($string);
  31. while ($i < $strlen) {
  32. if ($tmp_string[$i] == ' ') {
  33. $tmp_string = substr($tmp_string, 0, $i);
  34. $return .= strrev ($tmp_string);
  35. }
  36. $i++;
  37. }
  38. return $return;
  39. return substr($string, 0, $start) . $rep . substr($string, - $end);
  40. }

Report this snippet  

You need to login to post a comment.