3 * Class to convert HTML to Markdown with PHP Markdown Extra syntax support.
6 * @author Milian Wolff (<mail@milianw.de>, <http://milianw.de>)
7 * @license LGPL, see LICENSE_LGPL.txt and the summary below
8 * @copyright (C) 2007 Milian Wolff
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 * standard Markdownify class
28 require_once dirname(__FILE__).'/markdownify.php';
30 class Markdownify_Extra extends Markdownify {
32 * table data, including rows with content and the maximum width of each col
50 * constructor, see Markdownify::Markdownify() for more information
52 function Markdownify_Extra($linksAfterEachParagraph = MDFY_LINKS_EACH_PARAGRAPH, $bodyWidth = MDFY_BODYWIDTH, $keepHTML = MDFY_KEEPHTML) {
53 parent::Markdownify($linksAfterEachParagraph, $bodyWidth, $keepHTML);
55 ### new markdownable tags & attributes
56 # header ids: # foo {bar}
57 $this->isMarkdownable['h1']['id'] = 'optional';
58 $this->isMarkdownable['h2']['id'] = 'optional';
59 $this->isMarkdownable['h3']['id'] = 'optional';
60 $this->isMarkdownable['h4']['id'] = 'optional';
61 $this->isMarkdownable['h5']['id'] = 'optional';
62 $this->isMarkdownable['h6']['id'] = 'optional';
64 $this->isMarkdownable['table'] = array();
65 $this->isMarkdownable['th'] = array(
66 'align' => 'optional',
68 $this->isMarkdownable['td'] = array(
69 'align' => 'optional',
71 $this->isMarkdownable['tr'] = array();
72 array_push($this->ignore, 'thead');
73 array_push($this->ignore, 'tbody');
74 array_push($this->ignore, 'tfoot');
76 $this->isMarkdownable['dl'] = array();
77 $this->isMarkdownable['dd'] = array();
78 $this->isMarkdownable['dt'] = array();
80 $this->isMarkdownable['fnref'] = array(
81 'target' => 'required',
83 $this->isMarkdownable['footnotes'] = array();
84 $this->isMarkdownable['fn'] = array(
87 $this->parser->blockElements['fnref'] = false;
88 $this->parser->blockElements['fn'] = true;
89 $this->parser->blockElements['footnotes'] = true;
91 $this->isMarkdownable['abbr'] = array(
92 'title' => 'required',
94 # build RegEx lookahead to decide wether table can pe parsed or not
95 $inlineTags = array_keys($this->parser->blockElements, false);
96 $colContents = '(?:[^<]|<(?:'.implode('|', $inlineTags).'|[^a-z]))+';
97 $this->tableLookaheadHeader = '{
98 ^\s*(?:<thead\s*>)?\s* # open optional thead
99 <tr\s*>\s*(?: # start required row with headers
100 <th(?:\s+align=("|\')(?:left|center|right)\1)?\s*> # header with optional align
101 \s*'.$colContents.'\s* # contents
102 </th>\s* # close header
103 )+</tr> # close row with headers
104 \s*(?:</thead>)? # close optional thead
106 $this->tdSubstitute = '\s*'.$colContents.'\s* # contents
108 $this->tableLookaheadBody = '{
109 \s*(?:<tbody\s*>)?\s* # open optional tbody
110 (?:<tr\s*>\s* # start row
111 %s # cols to be substituted
113 \s*(?:</tbody>)? # close optional tbody
114 \s*</table> # close table
118 * handle header tags (<h1> - <h6>)
120 * @param int $level 1-6
123 function handleHeader($level) {
125 if ($this->parser->isStartTag) {
126 if (isset($this->parser->tagAttributes['id'])) {
127 $id = $this->parser->tagAttributes['id'];
131 $this->out(' {#'.$id.'}');
135 parent::handleHeader($level);
143 function handleTag_abbr() {
144 if ($this->parser->isStartTag) {
148 $tag = $this->unstack();
149 $tag['text'] = $this->unbuffer();
151 foreach ($this->stack['abbr'] as $stacked) {
152 if ($stacked['text'] == $tag['text']) {
153 /** TODO: differing abbr definitions, i.e. different titles for same text **/
158 $this->out($tag['text']);
160 array_push($this->stack['abbr'], $tag);
165 * flush stacked abbr tags
170 function flushStacked_abbr() {
172 foreach ($this->stack['abbr'] as $k => $tag) {
173 if (!isset($tag['unstacked'])) {
174 array_push($out, ' *['.$tag['text'].']: '.$tag['title']);
175 $tag['unstacked'] = true;
176 $this->stack['abbr'][$k] = $tag;
180 $this->out("\n\n".implode("\n", $out));
184 * handle <table> tags
189 function handleTag_table() {
190 if ($this->parser->isStartTag) {
191 # check if upcoming table can be converted
192 if ($this->keepHTML) {
193 if (preg_match($this->tableLookaheadHeader, $this->parser->html, $matches)) {
194 # header seems good, now check body
195 # get align & number of cols
196 preg_match_all('#<th(?:\s+align=("|\')(left|right|center)\1)?\s*>#si', $matches[0], $cols);
200 foreach ($cols[2] as $align) {
201 $align = strtolower($align);
202 array_push($aligns, $align);
204 $align = 'left'; # default value
206 $td = '\s+align=("|\')'.$align.'\\'.$i;
208 if ($align == 'left') {
209 # look for empty align or left
210 $td = '(?:'.$td.')?';
212 $td = '<td'.$td.'\s*>';
213 $regEx .= $td.$this->tdSubstitute;
215 $regEx = sprintf($this->tableLookaheadBody, $regEx);
216 if (preg_match($regEx, $this->parser->html, $matches, null, strlen($matches[0]))) {
217 # this is a markdownable table tag!
218 $this->table = array(
220 'col_widths' => array(),
225 # non markdownable table
226 $this->handleTagToText();
229 # non markdownable table
230 $this->handleTagToText();
233 $this->table = array(
235 'col_widths' => array(),
241 # finally build the table in Markdown Extra syntax
242 $separator = array();
243 # seperator with correct align identifikators
244 foreach($this->table['aligns'] as $col => $align) {
245 if (!$this->keepHTML && !isset($this->table['col_widths'][$col])) {
261 array_push($separator, $left.str_repeat('-', $this->table['col_widths'][$col]).$right);
263 $separator = '|'.implode('|', $separator).'|';
267 array_walk_recursive($this->table['rows'], array(&$this, 'alignTdContent'));
268 $header = array_shift($this->table['rows']);
269 array_push($rows, '| '.implode(' | ', $header).' |');
270 array_push($rows, $separator);
271 foreach ($this->table['rows'] as $row) {
272 array_push($rows, '| '.implode(' | ', $row).' |');
274 $this->out(implode("\n".$this->indent, $rows));
275 $this->table = array();
276 $this->setLineBreaks(2);
280 * properly pad content so it is aligned as whished
281 * should be used with array_walk_recursive on $this->table['rows']
283 * @param string &$content
287 function alignTdContent(&$content, $col) {
288 switch ($this->table['aligns'][$col]) {
291 $content .= str_repeat(' ', $this->table['col_widths'][$col] - $this->strlen($content));
294 $content = str_repeat(' ', $this->table['col_widths'][$col] - $this->strlen($content)).$content;
297 $paddingNeeded = $this->table['col_widths'][$col] - $this->strlen($content);
298 $left = floor($paddingNeeded / 2);
299 $right = $paddingNeeded - $left;
300 $content = str_repeat(' ', $left).$content.str_repeat(' ', $right);
310 function handleTag_tr() {
311 if ($this->parser->isStartTag) {
323 function handleTag_td() {
324 if ($this->parser->isStartTag) {
326 if (!isset($this->table['col_widths'][$this->col])) {
327 $this->table['col_widths'][$this->col] = 0;
331 $buffer = trim($this->unbuffer());
332 $this->table['col_widths'][$this->col] = max($this->table['col_widths'][$this->col], $this->strlen($buffer));
333 $this->table['rows'][$this->row][$this->col] = $buffer;
342 function handleTag_th() {
343 if (!$this->keepHTML && !isset($this->table['rows'][1]) && !isset($this->table['aligns'][$this->col+1])) {
344 if (isset($this->parser->tagAttributes['align'])) {
345 $this->table['aligns'][$this->col+1] = $this->parser->tagAttributes['align'];
347 $this->table['aligns'][$this->col+1] = '';
350 $this->handleTag_td();
358 function handleTag_dl() {
359 if (!$this->parser->isStartTag) {
360 $this->setLineBreaks(2);
369 function handleTag_dt() {
370 if (!$this->parser->isStartTag) {
371 $this->setLineBreaks(1);
380 function handleTag_dd() {
381 if ($this->parser->isStartTag) {
382 if (substr(ltrim($this->parser->html), 0, 3) == '<p>') {
383 # next comes a paragraph, so we'll need an extra line
384 $this->out("\n".$this->indent);
385 } elseif (substr($this->output, -2) == "\n\n") {
386 $this->output = substr($this->output, 0, -1);
389 $this->indent(' ', false);
391 # lookahead for next dt
392 if (substr(ltrim($this->parser->html), 0, 4) == '<dt>') {
393 $this->setLineBreaks(2);
395 $this->setLineBreaks(1);
401 * handle <fnref /> tags (custom footnote references, see markdownify_extra::parseString())
406 function handleTag_fnref() {
407 $this->out('[^'.$this->parser->tagAttributes['target'].']');
410 * handle <fn> tags (custom footnotes, see markdownify_extra::parseString()
411 * and markdownify_extra::_makeFootnotes())
416 function handleTag_fn() {
417 if ($this->parser->isStartTag) {
418 $this->out('[^'.$this->parser->tagAttributes['name'].']:');
419 $this->setLineBreaks(1);
421 $this->setLineBreaks(2);
426 * handle <footnotes> tag (custom footnotes, see markdownify_extra::parseString()
427 * and markdownify_extra::_makeFootnotes())
432 function handleTag_footnotes() {
433 if (!$this->parser->isStartTag) {
434 $this->setLineBreaks(2);
438 * parse a HTML string, clean up footnotes prior
440 * @param string $HTML input
441 * @return string Markdown formatted output
443 function parseString($html) {
444 /** TODO: custom markdown-extra options, e.g. titles & classes **/
445 # <sup id="fnref:..."><a href"#fn..." rel="footnote">...</a></sup>
446 # => <fnref target="..." />
447 $html = preg_replace('@<sup id="fnref:([^"]+)">\s*<a href="#fn:\1" rel="footnote">\s*\d+\s*</a>\s*</sup>@Us', '<fnref target="$1" />', $html);
448 # <div class="footnotes">
452 # <li id="fn:...">...</li>
459 # <fn name="...">...</fn>
462 $html = preg_replace_callback('#<div class="footnotes">\s*<hr />\s*<ol>\s*(.+)\s*</ol>\s*</div>#Us', array(&$this, '_makeFootnotes'), $html);
463 return parent::parseString($html);
466 * replace HTML representation of footnotes with something more easily parsable
468 * @note this is a callback to be used in parseString()
470 * @param array $matches
473 function _makeFootnotes($matches) {
476 # <a href="#fnref:block" rev="footnote">↩</a></p>
478 # => <fn name="1">...</fn>
479 # remove footnote link
480 $fns = preg_replace('@\s*( \s*)?<a href="#fnref:[^"]+" rev="footnote"[^>]*>↩</a>\s*@s', '', $matches[1]);
481 # remove empty paragraph
482 $fns = preg_replace('@<p>\s*</p>@s', '', $fns);
483 # <li id="fn:1">...</li> -> <footnote nr="1">...</footnote>
484 $fns = str_replace('<li id="fn:', '<fn name="', $fns);
486 $fns = '<footnotes>'.$fns.'</footnotes>';
487 return preg_replace('#</li>\s*(?=(?:<fn|</footnotes>))#s', '</fn>$1', $fns);