3 * Markdownify converts HTML Markup to [Markdown][1] (by [John Gruber][2]. It
4 * also supports [Markdown Extra][3] by [Michel Fortin][4] via Markdownify_Extra.
6 * It all started as `html2text.php` - a port of [Aaron Swartz'][5] [`html2text.py`][6] - but
7 * got a long way since. This is far more than a mere port now!
8 * Starting with version 2.0.0 this is a complete rewrite and cannot be
9 * compared to Aaron Swatz' `html2text.py` anylonger. I'm now using a HTML parser
10 * (see `parsehtml.php` which I also wrote) which makes most of the evil
11 * RegEx magic go away and additionally it gives a much cleaner class
12 * structure. Also notably is the fact that I now try to prevent regressions by
13 * utilizing testcases of Michel Fortin's [MDTest][7].
15 * [1]: http://daringfireball.com/projects/markdown
16 * [2]: http://daringfireball.com/
17 * [3]: http://www.michelf.com/projects/php-markdown/extra/
18 * [4]: http://www.michelf.com/
19 * [5]: http://www.aaronsw.com/
20 * [6]: http://www.aaronsw.com/2002/html2text/
21 * [7]: http://article.gmane.org/gmane.text.markdown.general/2540
23 * @version 2.0.0 alpha
24 * @author Milian Wolff (<mail@milianw.de>, <http://milianw.de>)
25 * @license LGPL, see LICENSE_LGPL.txt and the summary below
26 * @copyright (C) 2007 Milian Wolff
28 * This library is free software; you can redistribute it and/or
29 * modify it under the terms of the GNU Lesser General Public
30 * License as published by the Free Software Foundation; either
31 * version 2.1 of the License, or (at your option) any later version.
33 * This library is distributed in the hope that it will be useful,
34 * but WITHOUT ANY WARRANTY; without even the implied warranty of
35 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
36 * Lesser General Public License for more details.
38 * You should have received a copy of the GNU Lesser General Public
39 * License along with this library; if not, write to the Free Software
40 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
44 * HTML Parser, see http://sf.net/projects/parseHTML
46 require_once dirname(__FILE__).'/parsehtml/parsehtml.php';
49 * default configuration
51 define('MDFY_LINKS_EACH_PARAGRAPH', false);
52 define('MDFY_BODYWIDTH', false);
53 define('MDFY_KEEPHTML', true);
56 * HTML to Markdown converter class
72 * stack with tags which where not converted to html
76 var $notConverted = array();
78 * skip conversion to markdown
82 var $skipConversion = false;
85 * keep html tags which cannot be converted to markdown
89 var $keepHTML = false;
91 * wrap output, set to 0 to skip wrapping
101 var $minBodyWidth = 25;
103 * display links after each paragraph
107 var $linksAfterEachParagraph = false;
109 * constructor, set options, setup parser
111 * @param bool $linksAfterEachParagraph wether or not to flush stacked links after each paragraph
113 * @param int $bodyWidth wether or not to wrap the output to the given width
115 * @param bool $keepHTML wether to keep non markdownable HTML or to discard it
116 * defaults to true (HTML will be kept)
119 function Markdownify($linksAfterEachParagraph = MDFY_LINKS_EACH_PARAGRAPH, $bodyWidth = MDFY_BODYWIDTH, $keepHTML = MDFY_KEEPHTML) {
120 $this->linksAfterEachParagraph = $linksAfterEachParagraph;
121 $this->keepHTML = $keepHTML;
123 if ($bodyWidth > $this->minBodyWidth) {
124 $this->bodyWidth = intval($bodyWidth);
126 $this->bodyWidth = false;
129 $this->parser = new parseHTML;
130 $this->parser->noTagsInCode = true;
132 # we don't have to do this every time
135 foreach ($this->escapeInText as $s => $r) {
136 array_push($search, '#(?<!\\\)'.$s.'#U');
137 array_push($replace, $r);
139 $this->escapeInText = array(
141 'replace' => $replace
145 * parse a HTML string
147 * @param string $html
148 * @return string markdown formatted
150 function parseString($html) {
151 $this->parser->html = $html;
153 return $this->output;
156 * tags with elements which can be handled by markdown
160 var $isMarkdownable = array(
166 'blockquote' => array(),
170 'href' => 'required',
171 'title' => 'optional',
180 'title' => 'optional',
191 * html tags to be ignored (contents will be parsed)
200 * html tags to be dropped (contents will not be parsed!)
215 * Markdown indents which could be wrapped
216 * @note: use strings in regex format
220 var $wrappableIndents = array(
228 * list of chars which have to be escaped in normal text
229 * @note: use strings in regex format
233 * TODO: what's with block chars / sequences at the beginning of a block?
235 var $escapeInText = array(
236 '([-*_])([ ]{0,2}\1){2,}' => '\\\\$0|', # hr
237 '\*\*([^*\s]+)\*\*' => '\*\*$1\*\*', # strong
238 '\*([^*\s]+)\*' => '\*$1\*', # em
239 '__(?! |_)(.+)(?!<_| )__' => '\_\_$1\_\_', # em
240 '_(?! |_)(.+)(?!<_| )_' => '\_$1\_', # em
241 '`(.+)`' => '\`$1\`', # code
242 '\[(.+)\](\s*\()' => '\[$1\]$2', # links: [text] (url) => [text\] (url)
243 '\[(.+)\](\s*)\[(.*)\]' => '\[$1\]$2\[$3\]', # links: [text][id] => [text\][id\]
246 * wether last processed node was a block tag or not
250 var $lastWasBlockTag = false;
252 * name of last closed tag
256 var $lastClosedTag = '';
258 * iterate through the nodes and decide what we
259 * shall do with the current node
267 $this->parser->html = preg_replace('#<('.implode('|', $this->drop).')[^>]*>.*</\\1>#sU', '', $this->parser->html);
268 while ($this->parser->nextNode()) {
269 switch ($this->parser->nodeType) {
274 if ($this->keepHTML) {
275 $this->flushLinebreaks();
276 $this->out($this->parser->node);
277 $this->setLineBreaks(2);
285 if (in_array($this->parser->tagName, $this->ignore)) {
288 if ($this->parser->isStartTag) {
289 $this->flushLinebreaks();
291 if ($this->skipConversion) {
292 $this->isMarkdownable(); # update notConverted
293 $this->handleTagToText();
296 if (!$this->parser->keepWhitespace && $this->parser->isBlockElement && $this->parser->isStartTag) {
297 $this->parser->html = ltrim($this->parser->html);
299 if ($this->isMarkdownable()) {
300 if ($this->parser->isBlockElement && $this->parser->isStartTag && !$this->lastWasBlockTag && !empty($this->output)) {
301 if (!empty($this->buffer)) {
302 $str =& $this->buffer[count($this->buffer) -1];
304 $str =& $this->output;
306 if (substr($str, -strlen($this->indent)-1) != "\n".$this->indent) {
307 $str .= "\n".$this->indent;
310 $func = 'handleTag_'.$this->parser->tagName;
312 if ($this->linksAfterEachParagraph && $this->parser->isBlockElement && !$this->parser->isStartTag && empty($this->parser->openTags)) {
313 $this->flushStacked();
315 if (!$this->parser->isStartTag) {
316 $this->lastClosedTag = $this->parser->tagName;
319 $this->handleTagToText();
320 $this->lastClosedTag = '';
324 trigger_error('invalid node type', E_USER_ERROR);
327 $this->lastWasBlockTag = $this->parser->nodeType == 'tag' && $this->parser->isStartTag && $this->parser->isBlockElement;
329 if (!empty($this->buffer)) {
330 trigger_error('buffer was not flushed, this is a bug. please report!', E_USER_WARNING);
331 while (!empty($this->buffer)) {
332 $this->out($this->unbuffer());
336 $this->output = rtrim(str_replace('&', '&', str_replace('<', '<', str_replace('>', '>', $this->output))));
337 # end parsing, flush stacked tags
338 $this->flushStacked();
339 $this->stack = array();
342 * check if current tag can be converted to Markdown
347 function isMarkdownable() {
348 if (!isset($this->isMarkdownable[$this->parser->tagName])) {
349 # simply not markdownable
352 if ($this->parser->isStartTag) {
354 if ($this->keepHTML) {
355 $diff = array_diff(array_keys($this->parser->tagAttributes), array_keys($this->isMarkdownable[$this->parser->tagName]));
357 # non markdownable attributes given
362 foreach ($this->isMarkdownable[$this->parser->tagName] as $attr => $type) {
363 if ($type == 'required' && !isset($this->parser->tagAttributes[$attr])) {
364 # required markdown attribute not given
371 array_push($this->notConverted, $this->parser->tagName.'::'.implode('/', $this->parser->openTags));
375 if (!empty($this->notConverted) && end($this->notConverted) === $this->parser->tagName.'::'.implode('/', $this->parser->openTags)) {
376 array_pop($this->notConverted);
383 * output all stacked tags
388 function flushStacked() {
390 foreach ($this->stack as $tag => $a) {
392 call_user_func(array(&$this, 'flushStacked_'.$tag));
397 * output link references (e.g. [1]: http://example.com "title");
402 function flushStacked_a() {
404 foreach ($this->stack['a'] as $k => $tag) {
405 if (!isset($tag['unstacked'])) {
408 $this->out("\n\n", true);
410 $this->out("\n", true);
412 $this->out(' ['.$tag['linkID'].']: '.$tag['href'].(isset($tag['title']) ? ' "'.$tag['title'].'"' : ''), true);
413 $tag['unstacked'] = true;
414 $this->stack['a'][$k] = $tag;
419 * flush enqued linebreaks
424 function flushLinebreaks() {
425 if ($this->lineBreaks && !empty($this->output)) {
426 $this->out(str_repeat("\n".$this->indent, $this->lineBreaks), true);
428 $this->lineBreaks = 0;
431 * handle non Markdownable tags
436 function handleTagToText() {
437 if (!$this->keepHTML) {
438 if (!$this->parser->isStartTag && $this->parser->isBlockElement) {
439 $this->setLineBreaks(2);
442 # dont convert to markdown inside this tag
443 /** TODO: markdown extra **/
444 if (!$this->parser->isEmptyTag) {
445 if ($this->parser->isStartTag) {
446 if (!$this->skipConversion) {
447 $this->skipConversion = $this->parser->tagName.'::'.implode('/', $this->parser->openTags);
450 if ($this->skipConversion == $this->parser->tagName.'::'.implode('/', $this->parser->openTags)) {
451 $this->skipConversion = false;
456 if ($this->parser->isBlockElement) {
457 if ($this->parser->isStartTag) {
458 if (in_array($this->parent(), array('ins', 'del'))) {
459 # looks like ins or del are block elements now
460 $this->out("\n", true);
463 if ($this->parser->tagName != 'pre') {
464 $this->out($this->parser->node."\n".$this->indent);
465 if (!$this->parser->isEmptyTag) {
468 $this->setLineBreaks(1);
470 $this->parser->html = ltrim($this->parser->html);
472 # don't indent inside <pre> tags
473 $this->out($this->parser->node);
475 $indent = $this->indent;
479 if (!$this->parser->keepWhitespace) {
480 $this->output = rtrim($this->output);
482 if ($this->parser->tagName != 'pre') {
484 $this->out("\n".$this->indent.$this->parser->node);
487 $this->out($this->parser->node);
489 $this->indent = $indent;
492 if (in_array($this->parent(), array('ins', 'del'))) {
493 # ins or del was block element
497 if ($this->parser->tagName == 'li') {
498 $this->setLineBreaks(1);
500 $this->setLineBreaks(2);
504 $this->out($this->parser->node);
506 if (in_array($this->parser->tagName, array('code', 'pre'))) {
507 if ($this->parser->isStartTag) {
510 # add stuff so cleanup just reverses this
511 $this->out(str_replace('<', '&lt;', str_replace('>', '&gt;', $this->unbuffer())));
522 function handleText() {
523 if ($this->hasParent('pre') && strpos($this->parser->node, "\n") !== false) {
524 $this->parser->node = str_replace("\n", "\n".$this->indent, $this->parser->node);
526 if (!$this->hasParent('code') && !$this->hasParent('pre')) {
528 $this->parser->node = $this->decode($this->parser->node);
529 if (!$this->skipConversion) {
530 # escape some chars in normal Text
531 $this->parser->node = preg_replace($this->escapeInText['search'], $this->escapeInText['replace'], $this->parser->node);
534 $this->parser->node = str_replace(array('"', '&apos'), array('"', '\''), $this->parser->node);
536 $this->out($this->parser->node);
537 $this->lastClosedTag = '';
540 * handle <em> and <i> tags
545 function handleTag_em() {
546 $this->out('*', true);
548 function handleTag_i() {
549 $this->handleTag_em();
552 * handle <strong> and <b> tags
557 function handleTag_strong() {
558 $this->out('**', true);
560 function handleTag_b() {
561 $this->handleTag_strong();
569 function handleTag_h1() {
570 $this->handleHeader(1);
578 function handleTag_h2() {
579 $this->handleHeader(2);
587 function handleTag_h3() {
588 $this->handleHeader(3);
596 function handleTag_h4() {
597 $this->handleHeader(4);
605 function handleTag_h5() {
606 $this->handleHeader(5);
614 function handleTag_h6() {
615 $this->handleHeader(6);
618 * number of line breaks before next inline output
622 * handle header tags (<h1> - <h6>)
624 * @param int $level 1-6
627 function handleHeader($level) {
628 if ($this->parser->isStartTag) {
629 $this->out(str_repeat('#', $level).' ', true);
631 $this->setLineBreaks(2);
640 function handleTag_p() {
641 if (!$this->parser->isStartTag) {
642 $this->setLineBreaks(2);
651 function handleTag_a() {
652 if ($this->parser->isStartTag) {
654 if (isset($this->parser->tagAttributes['title'])) {
655 $this->parser->tagAttributes['title'] = $this->decode($this->parser->tagAttributes['title']);
657 $this->parser->tagAttributes['title'] = null;
659 $this->parser->tagAttributes['href'] = $this->decode(trim($this->parser->tagAttributes['href']));
662 $tag = $this->unstack();
663 $buffer = $this->unbuffer();
665 if (empty($tag['href']) && empty($tag['title'])) {
666 # empty links... testcase mania, who would possibly do anything like that?!
667 $this->out('['.$buffer.']()', true);
671 if ($buffer == $tag['href'] && empty($tag['title'])) {
672 # <http://example.com>
673 $this->out('<'.$buffer.'>', true);
677 $bufferDecoded = $this->decode(trim($buffer));
678 if (substr($tag['href'], 0, 7) == 'mailto:' && 'mailto:'.$bufferDecoded == $tag['href']) {
679 if (is_null($tag['title'])) {
681 $this->out('<'.$bufferDecoded.'>', true);
684 # [mail@example.com][1]
686 # [1]: mailto:mail@example.com Title
687 $tag['href'] = 'mailto:'.$bufferDecoded;
690 $this->out('['.$buffer.']('.$tag['href'].' "'.$tag['title'].'")', true);
694 foreach ($this->stack['a'] as $tag2) {
695 if ($tag2['href'] == $tag['href'] && $tag2['title'] === $tag['title']) {
696 $tag['linkID'] = $tag2['linkID'];
700 if (!isset($tag['linkID'])) {
701 $tag['linkID'] = count($this->stack['a']) + 1;
702 array_push($this->stack['a'], $tag);
705 $this->out('['.$buffer.']['.$tag['linkID'].']', true);
710 * handle <img /> tags
715 function handleTag_img() {
716 if (!$this->parser->isStartTag) {
717 return; # just to be sure this is really an empty tag...
720 if (isset($this->parser->tagAttributes['title'])) {
721 $this->parser->tagAttributes['title'] = $this->decode($this->parser->tagAttributes['title']);
723 $this->parser->tagAttributes['title'] = null;
725 if (isset($this->parser->tagAttributes['alt'])) {
726 $this->parser->tagAttributes['alt'] = $this->decode($this->parser->tagAttributes['alt']);
728 $this->parser->tagAttributes['alt'] = null;
731 if (empty($this->parser->tagAttributes['src'])) {
732 # support for "empty" images... dunno if this is really needed
733 # but there are some testcases which do that...
734 if (!empty($this->parser->tagAttributes['title'])) {
735 $this->parser->tagAttributes['title'] = ' '.$this->parser->tagAttributes['title'].' ';
737 $this->out('!['.$this->parser->tagAttributes['alt'].']('.$this->parser->tagAttributes['title'].')', true);
740 $this->parser->tagAttributes['src'] = $this->decode($this->parser->tagAttributes['src']);
743 // ![Alt text](/path/to/img.jpg "Optional title")
744 if ($this->parser->tagAttributes['title'] != "")
745 $this->out('!['.$this->parser->tagAttributes['alt'].']('.$this->parser->tagAttributes['src'].' "'.$this->parser->tagAttributes['title'].'")', true);
747 $this->out('!['.$this->parser->tagAttributes['alt'].']('.$this->parser->tagAttributes['src'].')', true);
752 if (!empty($this->stack['a'])) {
753 foreach ($this->stack['a'] as $tag) {
754 if ($tag['href'] == $this->parser->tagAttributes['src']
755 && $tag['title'] === $this->parser->tagAttributes['title']) {
756 $link_id = $tag['linkID'];
761 $this->stack['a'] = array();
764 $link_id = count($this->stack['a']) + 1;
766 'href' => $this->parser->tagAttributes['src'],
767 'linkID' => $link_id,
768 'title' => $this->parser->tagAttributes['title']
770 array_push($this->stack['a'], $tag);
773 $this->out('!['.$this->parser->tagAttributes['alt'].']['.$link_id.']', true);
782 function handleTag_code() {
783 if ($this->hasParent('pre')) {
784 # ignore code blocks inside <pre>
787 if ($this->parser->isStartTag) {
790 $buffer = $this->unbuffer();
791 # use as many backticks as needed
792 preg_match_all('#`+#', $buffer, $matches);
793 if (!empty($matches[0])) {
798 if (!in_array($ticks, $matches[0])) {
806 if ($buffer[0] == '`' || substr($buffer, -1) == '`') {
807 $buffer = ' '.$buffer.' ';
809 $this->out($ticks.$buffer.$ticks, true);
818 function handleTag_pre() {
819 if ($this->keepHTML && $this->parser->isStartTag) {
820 # check if a simple <code> follows
821 if (!preg_match('#^\s*<code\s*>#Us', $this->parser->html)) {
822 # this is no standard markdown code block
823 $this->handleTagToText();
828 if (!$this->parser->isStartTag) {
829 $this->setLineBreaks(2);
831 $this->parser->html = ltrim($this->parser->html);
835 * handle <blockquote> tags
840 function handleTag_blockquote() {
849 function handleTag_ul() {
850 if ($this->parser->isStartTag) {
852 if (!$this->keepHTML && $this->lastClosedTag == $this->parser->tagName) {
853 $this->out("\n".$this->indent.'<!-- -->'."\n".$this->indent."\n".$this->indent);
857 if ($this->parent() != 'li' || preg_match('#^\s*(</li\s*>\s*<li\s*>\s*)?<(p|blockquote)\s*>#sU', $this->parser->html)) {
858 # dont make Markdown add unneeded paragraphs
859 $this->setLineBreaks(2);
869 function handleTag_ol() {
871 $this->parser->tagAttributes['num'] = 0;
872 $this->handleTag_ul();
880 function handleTag_li() {
881 if ($this->parent() == 'ol') {
882 $parent =& $this->getStacked('ol');
883 if ($this->parser->isStartTag) {
885 $this->out($parent['num'].'.'.str_repeat(' ', 3 - strlen($parent['num'])), true);
887 $this->indent(' ', false);
889 if ($this->parser->isStartTag) {
890 $this->out('* ', true);
892 $this->indent(' ', false);
894 if (!$this->parser->isStartTag) {
895 $this->setLineBreaks(1);
904 function handleTag_hr() {
905 if (!$this->parser->isStartTag) {
906 return; # just to be sure this really is an empty tag
908 $this->out('* * *', true);
909 $this->setLineBreaks(2);
917 function handleTag_br() {
918 $this->out(" \n".$this->indent, true);
919 $this->parser->html = ltrim($this->parser->html);
922 * node stack, e.g. for <a> and <abbr> tags
926 var $stack = array();
928 * add current node to the stack
929 * this only stores the attributes
935 if (!isset($this->stack[$this->parser->tagName])) {
936 $this->stack[$this->parser->tagName] = array();
938 array_push($this->stack[$this->parser->tagName], $this->parser->tagAttributes);
941 * remove current tag from stack
947 if (!isset($this->stack[$this->parser->tagName]) || !is_array($this->stack[$this->parser->tagName])) {
948 trigger_error('Trying to unstack from empty stack. This must not happen.', E_USER_ERROR);
950 return array_pop($this->stack[$this->parser->tagName]);
953 * get last stacked element of type $tagName
955 * @param string $tagName
958 function & getStacked($tagName) {
959 // no end() so it can be referenced
960 return $this->stack[$tagName][count($this->stack[$tagName])-1];
963 * set number of line breaks before next start tag
968 function setLineBreaks($number) {
969 if ($this->lineBreaks < $number) {
970 $this->lineBreaks = $number;
974 * stores current buffers
978 var $buffer = array();
980 * buffer next parser output until unbuffer() is called
986 array_push($this->buffer, '');
989 * end current buffer and return buffered output
994 function unbuffer() {
995 return array_pop($this->buffer);
998 * append string to the correct var, either
999 * directly to $this->output or to the current
1002 * @param string $put
1005 function out($put, $nowrap = false) {
1009 if (!empty($this->buffer)) {
1010 $this->buffer[count($this->buffer) - 1] .= $put;
1012 if ($this->bodyWidth && !$this->parser->keepWhitespace) { # wrap lines
1014 $pos = strrpos($this->output, "\n");
1015 if ($pos === false) {
1016 $line = $this->output;
1018 $line = substr($this->output, $pos);
1022 if ($put[0] != "\n" && $this->strlen($line) + $this->strlen($put) > $this->bodyWidth) {
1023 $this->output .= "\n".$this->indent.$put;
1025 $this->output .= $put;
1029 $put .= "\n"; # make sure we get all lines in the while below
1030 $lineLen = $this->strlen($line);
1031 while ($pos = strpos($put, "\n")) {
1032 $putLine = substr($put, 0, $pos+1);
1033 $put = substr($put, $pos+1);
1034 $putLen = $this->strlen($putLine);
1035 if ($lineLen + $putLen < $this->bodyWidth) {
1036 $this->output .= $putLine;
1039 $split = preg_split('#^(.{0,'.($this->bodyWidth - $lineLen).'})\b#', $putLine, 2, PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_DELIM_CAPTURE);
1040 $this->output .= rtrim($split[1][0])."\n".$this->indent.$this->wordwrap(ltrim($split[2][0]), $this->bodyWidth, "\n".$this->indent, false);
1043 $this->output = substr($this->output, 0, -1);
1047 $this->output .= $put;
1052 * current indentation
1058 * indent next output (start tag) or unindent (end tag)
1060 * @param string $str indentation
1061 * @param bool $output add indendation to output
1064 function indent($str, $output = true) {
1065 if ($this->parser->isStartTag) {
1066 $this->indent .= $str;
1068 $this->out($str, true);
1071 $this->indent = substr($this->indent, 0, -strlen($str));
1075 * decode email addresses
1077 * @author derernst@gmx.ch <http://www.php.net/manual/en/function.html-entity-decode.php#68536>
1078 * @author Milian Wolff <http://milianw.de>
1080 function decode($text, $quote_style = ENT_QUOTES) {
1081 if (version_compare(PHP_VERSION, '5', '>=')) {
1082 # UTF-8 is only supported in PHP 5.x.x and above
1083 $text = html_entity_decode($text, $quote_style, 'UTF-8');
1085 if (function_exists('html_entity_decode')) {
1086 $text = html_entity_decode($text, $quote_style, 'ISO-8859-1');
1089 if (!isset($trans_tbl)) {
1090 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES, $quote_style));
1092 $text = strtr($text, $trans_tbl);
1094 $text = preg_replace_callback('~&#x([0-9a-f]+);~i', array(&$this, '_decode_hex'), $text);
1095 $text = preg_replace_callback('~&#(\d{2,5});~', array(&$this, '_decode_numeric'), $text);
1100 * callback for decode() which converts a hexadecimal entity to UTF-8
1102 * @param array $matches
1103 * @return string UTF-8 encoded
1105 function _decode_hex($matches) {
1106 return $this->unichr(hexdec($matches[1]));
1109 * callback for decode() which converts a numerical entity to UTF-8
1111 * @param array $matches
1112 * @return string UTF-8 encoded
1114 function _decode_numeric($matches) {
1115 return $this->unichr($matches[1]);
1118 * UTF-8 chr() which supports numeric entities
1120 * @author grey - greywyvern - com <http://www.php.net/manual/en/function.chr.php#55978>
1121 * @param array $matches
1122 * @return string UTF-8 encoded
1124 function unichr($dec) {
1127 } else if ($dec < 2048) {
1128 $utf = chr(192 + (($dec - ($dec % 64)) / 64));
1129 $utf .= chr(128 + ($dec % 64));
1131 $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
1132 $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
1133 $utf .= chr(128 + ($dec % 64));
1140 * @param string $str
1143 * @author dtorop 932 at hotmail dot com <http://www.php.net/manual/en/function.strlen.php#37975>
1144 * @author Milian Wolff <http://milianw.de>
1146 function strlen($str) {
1147 if (function_exists('mb_strlen')) {
1148 return mb_strlen($str, 'UTF-8');
1150 return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
1154 * wordwrap for utf8 encoded strings
1156 * @param string $str
1157 * @param integer $len
1158 * @param string $what
1161 function wordwrap($str, $width, $break, $cut = false){
1163 $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){1,'.$width.'}\b#';
1165 $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
1168 while (preg_match($regexp, $str, $matches)) {
1169 $string = $matches[0];
1170 $str = ltrim(substr($str, strlen($string)));
1171 if (!$cut && isset($str[0]) && in_array($str[0], array('.', '!', ';', ':', '?', ','))) {
1173 $str = ltrim(substr($str, 1));
1175 $return .= $string.$break;
1177 return $return.ltrim($str);
1180 * check if current node has a $tagName as parent (somewhere, not only the direct parent)
1182 * @param string $tagName
1185 function hasParent($tagName) {
1186 return in_array($tagName, $this->parser->openTags);
1189 * get tagName of direct parent tag
1192 * @return string $tagName
1195 return end($this->parser->openTags);