PHPackages                             cebe/markdown - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. cebe/markdown

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

cebe/markdown
=============

A super fast, highly extensible markdown parser for PHP

1.2.1(8y ago)1.0k32.5M—5.8%137[37 issues](https://github.com/cebe/markdown/issues)[7 PRs](https://github.com/cebe/markdown/pulls)20MITHTMLPHP &gt;=5.4.0CI failing

Since Feb 18Pushed 3y ago41 watchersCompare

[ Source](https://github.com/cebe/markdown)[ Packagist](https://packagist.org/packages/cebe/markdown)[ Docs](https://github.com/cebe/markdown#readme)[ RSS](/packages/cebe-markdown/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (17)Used By (20)

A super fast, highly extensible markdown parser for PHP
=======================================================

[](#a-super-fast-highly-extensible-markdown-parser-for-php)

[![Latest Stable Version](https://camo.githubusercontent.com/a66d5da6020dc8158936ccfbe7e9bbb64caa435d47190245308ed1e5a3ad4053/68747470733a2f2f706f7365722e707567782e6f72672f636562652f6d61726b646f776e2f762f737461626c652e706e67)](https://packagist.org/packages/cebe/markdown)[![Total Downloads](https://camo.githubusercontent.com/7c4ce6acd4e0ae9d081ed29a0cb8b6b816c762399d088a5c89fcdeaffc8afe50/68747470733a2f2f706f7365722e707567782e6f72672f636562652f6d61726b646f776e2f646f776e6c6f6164732e706e67)](https://packagist.org/packages/cebe/markdown)[![Build Status](https://camo.githubusercontent.com/fc7a8fd2dd5edf2a9b834c0e2e2d681238f09bfe4b676031eb5f175ea07de9f5/68747470733a2f2f7472617669732d63692e6f72672f636562652f6d61726b646f776e2e7376673f6272616e63683d6d6173746572)](http://travis-ci.org/cebe/markdown)[![Code Coverage](https://camo.githubusercontent.com/167d51dae262f0ee77cfb676f95fa973191aad68b7648daabc64de7cae01ce30/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f636562652f6d61726b646f776e2f6261646765732f636f7665726167652e706e673f733d64623661663334326435356265613634393330376566333131666264353336616262396261623736)](https://scrutinizer-ci.com/g/cebe/markdown/)[![Scrutinizer Quality Score](https://camo.githubusercontent.com/2c046ed7be2b7494bd5147427294132230536ea962245f8a5464f6f8d0e3da8e/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f636562652f6d61726b646f776e2f6261646765732f7175616c6974792d73636f72652e706e673f733d31373434386361346431343034323966643638376335386666373437626165623635363864353238)](https://scrutinizer-ci.com/g/cebe/markdown/)

What is this?
----------------------------------------------

[](#what-is-this-)

A set of [PHP](http://php.net/ "PHP is a popular general-purpose scripting language that is especially suited to web development.") classes, each representing a [Markdown](http://en.wikipedia.org/wiki/Markdown "Markdown on Wikipedia") flavor, and a command line tool for converting markdown files to HTML files.

The implementation focus is to be **fast** (see [benchmark](https://github.com/kzykhys/Markbench#readme "kzykhys/Markbench on github")) and **extensible**. Parsing Markdown to HTML is as simple as calling a single method (see [Usage](#usage)) providing a solid implementation that gives most expected results even in non-trivial edge cases.

Extending the Markdown language with new elements is as simple as adding a new method to the class that converts the markdown text to the expected output in HTML. This is possible without dealing with complex and error prone regular expressions. It is also possible to hook into the markdown structure and add elements or read meta information using the internal representation of the Markdown text as an abstract syntax tree (see [Extending the language](#extend)).

Currently the following markdown flavors are supported:

- **Traditional Markdown** according to  ([try it!](http://markdown.cebe.cc/try?flavor=default)).
- **Github flavored Markdown** according to  ([try it!](http://markdown.cebe.cc/try?flavor=gfm)).
- **Markdown Extra** according to  (currently not fully supported WIP see [\#25](https://github.com/cebe/markdown/issues/25 "issue #25"), [try it!](http://markdown.cebe.cc/try?flavor=extra))
- Any mixed Markdown flavor you like because of its highly extensible structure (See documentation below).

Future plans are to support:

- Smarty Pants
- ... (Feel free to [suggest](https://github.com/cebe/markdown/issues/new) further additions!)

### Who is using it?

[](#who-is-using-it)

- It powers the [API-docs and the definitive guide](http://www.yiiframework.com/doc-2.0/) for the [Yii Framework](http://www.yiiframework.com/ "The Yii PHP Framework") [2.0](https://github.com/yiisoft/yii2).

Installation
-----------------------------------------------------

[](#installation-)

[PHP 5.4 or higher](http://www.php.net/downloads.php) is required to use it. It will also run on facebook's [hhvm](http://hhvm.com/).

The library uses PHPDoc annotations to determine the markdown elements that should be parsed. So in case you are using PHP `opcache`, make sure [it does not strip comments](http://php.net/manual/en/opcache.configuration.php#ini.opcache.save-comments).

Installation is recommended to be done via [composer](https://getcomposer.org/ "The PHP package manager") by running:

```
composer require cebe/markdown "~1.2.0"

```

Alternatively you can add the following to the `require` section in your `composer.json` manually:

```
"cebe/markdown": "~1.2.0"
```

Run `composer update cebe/markdown` afterwards.

> Note: If you have configured PHP with opcache you need to enable the [opcache.save\_comments](http://php.net/manual/en/opcache.configuration.php#ini.opcache.save-comments) option because inline element parsing relies on PHPdoc annotations to find declared elements.

Usage
---------------------------------------

[](#usage-)

### In your PHP project

[](#in-your-php-project)

To parse your markdown you need only two lines of code. The first one is to choose the markdown flavor as one of the following:

- Traditional Markdown: `$parser = new \cebe\markdown\Markdown();`
- Github Flavored Markdown: `$parser = new \cebe\markdown\GithubMarkdown();`
- Markdown Extra: `$parser = new \cebe\markdown\MarkdownExtra();`

The next step is to call the `parse()`-method for parsing the text using the full markdown language or calling the `parseParagraph()`-method to parse only inline elements.

Here are some examples:

```
// traditional markdown and parse full text
$parser = new \cebe\markdown\Markdown();
echo $parser->parse($markdown);

// use github markdown
$parser = new \cebe\markdown\GithubMarkdown();
echo $parser->parse($markdown);

// use markdown extra
$parser = new \cebe\markdown\MarkdownExtra();
echo $parser->parse($markdown);

// parse only inline elements (useful for one-line descriptions)
$parser = new \cebe\markdown\GithubMarkdown();
echo $parser->parseParagraph($markdown);
```

You may optionally set one of the following options on the parser object:

For all Markdown Flavors:

- `$parser->html5 = true` to enable HTML5 output instead of HTML4.
- `$parser->keepListStartNumber = true` to enable keeping the numbers of ordered lists as specified in the markdown. The default behavior is to always start from 1 and increment by one regardless of the number in markdown.

For GithubMarkdown:

- `$parser->enableNewlines = true` to convert all newlines to ``-tags. By default only newlines with two preceding spaces are converted to ``-tags.

It is recommended to use UTF-8 encoding for the input strings. Other encodings may work, but are currently untested.

### The command line script

[](#the-command-line-script)

You can use it to render this readme:

```
bin/markdown README.md > README.html

```

Using github flavored markdown:

```
bin/markdown --flavor=gfm README.md > README.html

```

or convert the original markdown description to html using the unix pipe:

```
curl http://daringfireball.net/projects/markdown/syntax.text | bin/markdown > md.html

```

Here is the full Help output you will see when running `bin/markdown --help`:

```
PHP Markdown to HTML converter
------------------------------

by Carsten Brandt

Usage:
    bin/markdown [--flavor=] [--full] [file.md]

    --flavor  specifies the markdown flavor to use. If omitted the original markdown by John Gruber [1] will be used.
              Available flavors:

              gfm   - Github flavored markdown [2]
              extra - Markdown Extra [3]

    --full    ouput a full HTML page with head and body. If not given, only the parsed markdown will be output.

    --help    shows this usage information.

    If no file is specified input will be read from STDIN.

Examples:

    Render a file with original markdown:

        bin/markdown README.md > README.html

    Render a file using gihtub flavored markdown:

        bin/markdown --flavor=gfm README.md > README.html

    Convert the original markdown description to html using STDIN:

        curl http://daringfireball.net/projects/markdown/syntax.text | bin/markdown > md.html

[1] http://daringfireball.net/projects/markdown/syntax
[2] https://help.github.com/articles/github-flavored-markdown
[3] http://michelf.ca/projects/php-markdown/extra/

```

Security Considerations
------------------------------------------------------------

[](#security-considerations-)

By design markdown [allows HTML to be included within the markdown text](https://daringfireball.net/projects/markdown/syntax#html). This also means that it may contain Javascript and CSS styles. This allows to be very flexible for creating output that is not limited by the markdown syntax, but it comes with a security risk if you are parsing user input as markdown (see [XSS](https://en.wikipedia.org/wiki/Cross-site_scripting)).

In that case you should process the result of the markdown conversion with tools like [HTML Purifier](http://htmlpurifier.org/) that filter out all elements which are not allowed for users to be added.

The list of [allowed elements](http://htmlpurifier.org/live/configdoc/plain.html#HTML.AllowedElements) for markdown could be configured as:

```
[
    'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
    'hr',
    'pre', 'code',
    'blockquote',
    'table', 'tr', 'td', 'th', 'thead', 'tbody',
    'strong', 'em', 'b', 'i', 'u', 's', 'span',
    'a', 'p', 'br', 'nobr',
    'ul', 'ol', 'li',
    'img',
],
```

The list of [allowed attributes](http://htmlpurifier.org/live/configdoc/plain.html#HTML.AllowedAttributes) would be:

```
['th.align', 'td.align', 'ol.start', 'code.class']
```

The above configuration is a general recommendation and may need to be adjusted dependent on your needs.

Extensions
----------

[](#extensions)

Here are some extensions to this library:

- [Bogardo/markdown-codepen](https://github.com/Bogardo/markdown-codepen) - shortcode to embed codepens from  in markdown.
- [cebe/markdown-latex](https://github.com/cebe/markdown-latex) - Convert Markdown to LaTeX and PDF
- [softark/creole](https://github.com/softark/creole) - A creole markup parser
- [hyn/frontmatter](https://github.com/hyn/frontmatter) - Frontmatter Metadata Support (JSON, TOML, YAML)
- ... [add yours!](https://github.com/cebe/markdown/edit/master/README.md#L186)

Extending the language
---------------------------------------------------------

[](#extending-the-language-)

Markdown consists of two types of language elements, I'll call them block and inline elements simlar to what you have in HTML with `` and ``. Block elements are normally spreads over several lines and are separated by blank lines. The most basic block element is a paragraph (``). Inline elements are elements that are added inside of block elements i.e. inside of text.

This markdown parser allows you to extend the markdown language by changing existing elements behavior and also adding new block and inline elements. You do this by extending from the parser class and adding/overriding class methods and properties. For the different element types there are different ways to extend them as you will see in the following sections.

### Adding block elements

[](#adding-block-elements)

The markdown is parsed line by line to identify each non-empty line as one of the block element types. To identify a line as the beginning of a block element it calls all protected class methods who's name begins with `identify`. An identify function returns true if it has identified the block element it is responsible for or false if not. In the following example we will implement support for [fenced code blocks](https://help.github.com/articles/github-flavored-markdown#fenced-code-blocks "Fenced code block feature of github flavored markdown") which are part of the github flavored markdown.

```
