Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert HTML to markdown?

Tags:

html

php

markdown

I have a website like stackoverflow. There is a textarea which people write answers. I use this PHP library to convert markdown. I mean I use that function to convert *italic* to <i>italic</i>.

// include that library
$Parsedown = new Parsedown();
echo $Parsedown->text('*italic*'); # prints: <i>italic</i>

Well All fine. It should be noted I convert that answer (to html tags, not markdown symbols) befor storing, in other word, all data in the database are containing HTML tags, not markdown symbols.

Now I want to implement Editing-System for answers. Something exactly like stackoverflow. So I need to convert saved answer to markdown-style again.

Now I want to know, how can I reconvert it? I mean I want to convert <i>italic</i> to *italic*, How can I do that?

like image 461
stack Avatar asked Mar 17 '16 01:03

stack


2 Answers

I needed this too, I found these 2 github projects:

  • https://github.com/Elephant418/Markdownify
  • https://github.com/thephpleague/html-to-markdown

I used the first one, because it has support for Markdown Extra (converted with ParsedownExtra), and it worked well for me.

like image 93
Redzarf Avatar answered Oct 19 '22 15:10

Redzarf


Rather than storing the original input as parsed markdown, you should store the actual markdown and convert it to HTML only when rendering it to the page.

This way you retain the original markdown for editing as required. It is also more logical.

like image 41
Marty Avatar answered Oct 19 '22 15:10

Marty