Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function my_excerpt($maxLength=380){
- $html = get_the_content();
- mb_internal_encoding("UTF-8");
- $printedLength = 0;
- $position = 0;
- $tags = array();
- $out = "";
- while ($printedLength < $maxLength && mb_preg_match('{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position))
- {
- list($tag, $tagPosition) = $match[0];
- // Print text leading up to the tag.
- $str = mb_substr($html, $position, $tagPosition - $position);
- if ($printedLength + mb_strlen($str) > $maxLength)
- {
- $out .= mb_substr($str, 0, $maxLength - $printedLength);
- $printedLength = $maxLength;
- break;
- }
- $out .= $str;
- $printedLength += mb_strlen($str);
- if ($tag[0] == '&')
- {
- // Handle the entity.
- $out .= $tag;
- $printedLength++;
- }
- else
- {
- // Handle the tag.
- $tagName = $match[1][0];
- if ($tag[1] == '/')
- {
- // This is a closing tag.
- $openingTag = array_pop($tags);
- assert($openingTag == $tagName); // check that tags are properly nested.
- $out .= $tag;
- }
- else if ($tag[mb_strlen($tag) - 2] == '/')
- {
- // Self-closing tag.
- $out .= $tag;
- }
- else
- {
- // Opening tag.
- $out .= $tag;
- $tags[] = $tagName;
- }
- }
- // Continue after the tag.
- $position = $tagPosition + mb_strlen($tag);
- }
- // Print any remaining text.
- if ($printedLength < $maxLength && $position < mb_strlen($html))
- $out .= mb_substr($html, $position, $maxLength - $printedLength);
- // Close any open tags.
- while (!empty($tags))
- $out .= sprintf('</%s>', array_pop($tags));
- echo $out;
- }
- function mb_preg_match(
- $ps_pattern,
- $ps_subject,
- &$pa_matches,
- $pn_flags = 0,
- $pn_offset = 0,
- $ps_encoding = NULL
- ) {
- // WARNING! - All this function does is to correct offsets, nothing else:
- //(code is independent of PREG_PATTER_ORDER / PREG_SET_ORDER)
- if (is_null($ps_encoding)) $ps_encoding = mb_internal_encoding();
- $pn_offset = strlen(mb_substr($ps_subject, 0, $pn_offset, $ps_encoding));
- $ret = preg_match($ps_pattern, $ps_subject, $pa_matches, $pn_flags, $pn_offset);
- if ($ret && ($pn_flags & PREG_OFFSET_CAPTURE))
- foreach($pa_matches as &$ha_match) {
- $ha_match[1] = mb_strlen(substr($ps_subject, 0, $ha_match[1]), $ps_encoding);
- }
- return $ret;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement