'.
* @param array $list_stack Active list stack (modified by reference).
* @param bool $in_pre Inside flag (modified by reference).
* @return string Markdown replacement.
*/
private static function convert_tag( $tag, array &$list_stack, &$in_pre ) {
$is_closing = ( strlen( $tag ) > 1 && '/' === $tag[1] );
$name_match = array();
if ( ! preg_match( '#?([a-zA-Z0-9]+)#', $tag, $name_match ) ) {
return '';
}
$name = strtolower( $name_match[1] );
switch ( $name ) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return "\n\n" . str_repeat( '#', (int) $name[1] ) . ' ';
case 'p':
case 'div':
case 'section':
case 'article':
case 'header':
case 'footer':
case 'main':
case 'figure':
case 'figcaption':
return "\n\n";
case 'br':
return "\n";
case 'hr':
return "\n\n---\n\n";
case 'strong':
case 'b':
return '**';
case 'em':
case 'i':
return '*';
case 'code':
return '`';
case 'pre':
if ( $is_closing ) {
$in_pre = false;
return "\n```\n";
}
$in_pre = true;
return "\n```\n";
case 'blockquote':
return "\n\n> ";
case 'a':
case 'img':
// Already converted in the pre-pass; a stray tag here is dropped.
return '';
case 'ul':
case 'ol':
if ( $is_closing ) {
array_pop( $list_stack );
return "\n";
}
$list_stack[] = array( 'type' => $name, 'counter' => 0 );
return "\n";
case 'li':
if ( $is_closing ) {
return "\n";
}
$depth = max( 0, count( $list_stack ) - 1 );
$indent = str_repeat( ' ', $depth );
$context = end( $list_stack );
if ( false === $context ) {
return $indent . '- ';
}
if ( 'ol' === $context['type'] ) {
$list_stack[ count( $list_stack ) - 1 ]['counter']++;
$marker = $list_stack[ count( $list_stack ) - 1 ]['counter'] . '. ';
} else {
$marker = '- ';
}
return "\n" . $indent . $marker;
case 'table':
return "\n\n";
case 'thead':
case 'tbody':
case 'tfoot':
return '';
case 'tr':
return $is_closing ? "\n" : '| ';
case 'th':
case 'td':
return $is_closing ? ' | ' : '';
default:
// Unknown tags: drop the tag, keep content flowing.
return '';
}
}
/**
* Decode a text node for output.
*
* @param string $text Raw text.
* @return string
*/
private static function decode_text( $text ) {
return html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
}
/**
* Escape characters that would be interpreted as Markdown syntax
* inside plain text runs.
*
* @param string $text Decoded text.
* @return string
*/
private static function escape_markdown_chars( $text ) {
$text = str_replace( '\\', '\\\\', $text );
$text = preg_replace( '/(?]+)/i';
if ( ! preg_match( $pattern, $tag, $m ) ) {
return '';
}
if ( isset( $m[2] ) && '' !== $m[2] ) {
$value = $m[2];
} elseif ( isset( $m[1] ) && '' !== $m[1] ) {
$value = $m[1];
} else {
$value = $m[0];
}
return self::decode_text( $value );
}
}