erusev / parsedown

Better Markdown Parser in PHP
https://parsedown.org
MIT License
14.79k stars 1.12k forks source link

Video Support #849

Open pixlmint opened 1 year ago

pixlmint commented 1 year ago

The goal is to allow videos to be embedded just like images

In GitHub Markdown that works by having the link to a video surrounded by 2 empty lines. According to some blogs, in regular Markdown that's supposed to work exactly like with images, so like ![video title](video link). Now, perhaps Parsedown already has this, but if so then it doesn't work with .webm video files.

And just to clarify, when I talk about embedding I don't mean from sites like YouTube, but actual Video files

peterujah commented 1 year ago

To do this you can extend the class and create a blockMedia like below.

<?php 
class Markdown extends \Parsedown{
  public function __construct(){
    $this->BlockTypes["{"] = array('Media');
    $this->InlineTypes["{"] = array('Media');
  }

    protected function blockMedia($Line, $Block = null) {
        if (preg_match('/^(\s*)\{(.+?)\}\((.+?)\)\((\S+?)\)$/', $Line['body'], $matches)){

            $description = $matches[2];
            $type = $matches[3];
            $link = $matches[4];

            $html = '';
            if (strtolower($type) === 'video') {
                $html .= '<video controls>';
            } else {
                $html .= '<audio controls>';
            }
            $html .= '<source src="' . htmlspecialchars($link) . '">';
            if (strtolower($type) === 'video') {
                $html .= '</video>';
            } else {
                $html .= '</audio>';
            }
            $html .= '<p>' . htmlspecialchars($description) . ' (' . htmlspecialchars($type) . ')</p>';

            $Block = array(
                'markup' => $html,
            );

            return $Block;
        }
    }

}

Now to format video use this {Video Description}(video)(https://example.com/video.mp4) {Audio Description}(audio)(https://example.com/audio.mp3)