简体   繁体   中英

Display markdown images as links

I'm using Michel Fortin's PHP Markdown for Markdown converting but i want to show images as links instead of inline. Because anyone can insert a 5MB jpg from Imgur and slow down page.

How can i change images to link-to-image?

An example of an override would look something like the follwing:

class CustomMarkdown extends Markdown
{
    function _doImages_reference_callback($matches) {
        $whole_match = $matches[1];
        $alt_text    = $matches[2];
        $link_id     = strtolower($matches[3]);

        if ($link_id == "") {
            $link_id = strtolower($alt_text); # for shortcut links like ![this][].
        }

        $alt_text = $this->encodeAttribute($alt_text);
        if (isset($this->urls[$link_id])) {
            $url = $this->encodeAttribute($this->urls[$link_id]);
            $result = "<a href=\"$url\">$alt_text</a>";
        } else {
            # If there's no such link ID, leave intact:
            $result = $whole_match;
        }

        return $result;
    }

    function _doImages_inline_callback($matches) {
        $whole_match    = $matches[1];
        $alt_text       = $matches[2];
        $url            = $matches[3] == '' ? $matches[4] : $matches[3];
        $title          =& $matches[7];

        $alt_text = $this->encodeAttribute($alt_text);
        $url = $this->encodeAttribute($url);
        return "<a href=\"$url\">$alt_text</a>";
    }
}

Demo: http://codepad.viper-7.com/VVa2hP

You should have a look at Parsedown . It is a more recent and, I believe, easier to extend implementation of Markdown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM