league/commonmark

repository·2.8·Indexed 25 days ago

https://github.com/thephpleague/commonmark

A highly-extensible PHP Markdown parser supporting the full CommonMark specification and GitHub-Flavored Markdown (GFM). It provides classes like CommonMarkConverter and GithubFlavoredMarkdownConverter for converting Markdown to HTML, and supports AST document processors, custom extensions, and a configurable environment for flexible parsing and rendering.

Tokens
66.7K
Snippets
154
Records
309
Agent score
83%

What's inside league/commonmark

  1. Convert Markdown to HTML using CommonMarkConverter

    2.8

    For standard CommonMark conversion, use the CommonMarkConverter class. It provides a simple wrapper to convert Markdown strings into HTML.

    Important: Review the security documentation to avoid security misconfigurations when rendering HTML.

    require __DIR__ . '/vendor/autoload.php';
    
    use League\CommonMark\CommonMarkConverter;
    
    $converter = new CommonMarkConverter();
    echo $converter->convertToHtml('# Hello World!');
    
    // <h1>Hello World!</h1>
  2. Best practices for additional HTML filtering

    2.8
    If you choose to run the generated HTML through additional post-processing layers (such as HTMLPurifier), ensure you thoroughly test the integration. Improper configuration of post-processors can lead to broken links, missing images, or mismatched HTML tags in the final output.
  3. Customize rendering for Mention objects

    2.8

    When using the Mention extension, every detected mention is added to the document's Abstract Syntax Tree (AST) as a Mention object. By default, Mention extends Link, so it renders as a standard HTML <a> tag.

    To change the HTML output of mentions, you can implement a custom renderer for the Mention type.

  4. Use the Task List Extension

    2.8

    The TaskListExtension adds support for GitHub Flavored Markdown (GFM) style task lists (e.g., - [x] for completed and - [ ] for incomplete tasks).

    Note that this extension is already included by default when using the GitHub Flavored Markdown extension.

    This extension only handles the Markdown parsing and HTML rendering; it does not provide any JavaScript to make the checkboxes interactive. You must implement your own JavaScript logic if you want users to be able to check or uncheck boxes in the browser.

    use League\CommonMark\Environment;
    use League\CommonMark\Extension\TaskList\TaskListExtension;
    use League\CommonMark\MarkdownConverter;
    
    // Obtain a pre-configured Environment
    $environment = Environment::createCommonMarkEnvironment();
    
    // Add the TaskListExtension
    $environment->addExtension(new TaskListExtension());
    
    // Instantiate the converter engine
    $converter = new MarkdownConverter($environment);
    
    $markdown = <<<'EOT';
     - [x] Install this extension
     - [ ] ???
     - [ ] Profit!
    EOT;
    
    echo $converter->convertToHtml($markdown);
  5. Configure HTML input handling for security

    2.8

    By default, all HTML input is unescaped to comply with the CommonMark spec. If you are rendering untrusted user input, you must configure the html_input option to prevent Cross-Site Scripting (XSS) attacks.

    Available options for html_input:

    • escape: Converts all raw HTML into escaped entities (e.g., < becomes &lt;).
    • strip: Removes all HTML tags from the input entirely.
  6. Use the Mention Extension

    2.8

    The MentionExtension allows you to parse shortened references like @username or #123 into custom URLs. You can configure it by adding the extension to your Environment and defining mention rules in the mentions configuration key. Each rule requires a prefix, a pattern (regex), and a generator.

    use League//CommonMark/Environment;
    use League//CommonMark/Extension/Mention/MentionExtension;
    use League//CommonMark/MarkdownConverter;
    
    $environment = Environment::createCommonMarkEnvironment();
    $environment->addExtension(new MentionExtension());
    
    $environment->mergeConfig([
        'mentions' => [
            'github_handle' => [
                'prefix'    => '@',
                'pattern'   => '[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}(?!\w)',
                'generator' => 'https://github.com/%s',
            ],
        ],
    ]);
    
    $converter = new MarkdownConverter($environment);
    echo $converter->convertToHtml('Follow me: @colinodell');
  7. Install the Front Matter Extension

    2.8

    The FrontMatterExtension is bundled with league/commonmark. To use it, you must also install a YAML parser. You can use either symfony/yaml (version 2.6 or higher) or the PHP YAML extension.

    If both are installed, the PHP YAML extension will be used by default.

    Security Warning: If using the PHP YAML extension, ensure yaml.decode_php=1 is not set in your php.ini, as this enables deserialization of arbitrary classes and can lead to security vulnerabilities.

  8. Implement a custom Delimiter Processor

    2.8

    Use Delimiter Processors to implement syntax that wraps text with specific characters (e.g., *emphasis* or {syntax}). This is preferred over basic inline parsers when your syntax requires matching characters both before and after the content.

    To implement a standalone processor, implement the DelimiterProcessorInterface and register it with your environment:

    $environment->addDelimiterProcessor(new MyCustomDelimiterProcessor());

    Note on Priority: Delimiter processors have a lower priority than inline parsers. If an inline parser successfully handles a character, your delimiter processor will not be called.