Advertisement
Guest User

Untitled

a guest
Dec 6th, 2012
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. function my_excerpt($maxLength=380){
  2.  
  3. $html = get_the_content();
  4.  
  5. mb_internal_encoding("UTF-8");
  6. $printedLength = 0;
  7. $position = 0;
  8. $tags = array();
  9. $out = "";
  10.  
  11. while ($printedLength < $maxLength && mb_preg_match('{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position))
  12. {
  13. list($tag, $tagPosition) = $match[0];
  14.  
  15. // Print text leading up to the tag.
  16. $str = mb_substr($html, $position, $tagPosition - $position);
  17. if ($printedLength + mb_strlen($str) > $maxLength)
  18. {
  19. $out .= mb_substr($str, 0, $maxLength - $printedLength);
  20. $printedLength = $maxLength;
  21. break;
  22. }
  23.  
  24. $out .= $str;
  25. $printedLength += mb_strlen($str);
  26.  
  27. if ($tag[0] == '&')
  28. {
  29. // Handle the entity.
  30. $out .= $tag;
  31. $printedLength++;
  32. }
  33. else
  34. {
  35. // Handle the tag.
  36. $tagName = $match[1][0];
  37. if ($tag[1] == '/')
  38. {
  39. // This is a closing tag.
  40.  
  41. $openingTag = array_pop($tags);
  42. assert($openingTag == $tagName); // check that tags are properly nested.
  43.  
  44. $out .= $tag;
  45. }
  46. else if ($tag[mb_strlen($tag) - 2] == '/')
  47. {
  48. // Self-closing tag.
  49. $out .= $tag;
  50. }
  51. else
  52. {
  53. // Opening tag.
  54. $out .= $tag;
  55. $tags[] = $tagName;
  56. }
  57. }
  58.  
  59. // Continue after the tag.
  60. $position = $tagPosition + mb_strlen($tag);
  61. }
  62.  
  63. // Print any remaining text.
  64. if ($printedLength < $maxLength && $position < mb_strlen($html))
  65. $out .= mb_substr($html, $position, $maxLength - $printedLength);
  66.  
  67. // Close any open tags.
  68. while (!empty($tags))
  69. $out .= sprintf('</%s>', array_pop($tags));
  70.  
  71. echo $out;
  72. }
  73.  
  74. function mb_preg_match(
  75. $ps_pattern,
  76. $ps_subject,
  77. &$pa_matches,
  78. $pn_flags = 0,
  79. $pn_offset = 0,
  80. $ps_encoding = NULL
  81. ) {
  82. // WARNING! - All this function does is to correct offsets, nothing else:
  83. //(code is independent of PREG_PATTER_ORDER / PREG_SET_ORDER)
  84.  
  85. if (is_null($ps_encoding)) $ps_encoding = mb_internal_encoding();
  86.  
  87. $pn_offset = strlen(mb_substr($ps_subject, 0, $pn_offset, $ps_encoding));
  88. $ret = preg_match($ps_pattern, $ps_subject, $pa_matches, $pn_flags, $pn_offset);
  89.  
  90. if ($ret && ($pn_flags & PREG_OFFSET_CAPTURE))
  91. foreach($pa_matches as &$ha_match) {
  92. $ha_match[1] = mb_strlen(substr($ps_subject, 0, $ha_match[1]), $ps_encoding);
  93. }
  94.  
  95. return $ret;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement