html和markdown互转
来源:learnku.com 更新时间:2023-05-25 21:55
使用
<?php
namespace App\Http\Controllers\Traits;
use League\HTMLToMarkdown\HtmlConverter;
trait Markdown
{
/**
* markdown -> html
* @param $markdown
* @return mixed
*/
public function markdownToHtml($markdown)
{
// markdown to html
$convertedHmtl = app('Parsedown')->setBreaksEnabled(true)->text($markdown);
/** XSS 防注入 */
$convertedHmtl = clean($convertedHmtl, 'markdown');
// 代码高亮展示优化
$convertedHmtl = str_replace("<pre><code>", '<pre><code class=" language-php">', $convertedHmtl);
// 移除 {{}}
// $convertedHmtl = remove_vue($convertedHmtl);
// 返回 html
return $convertedHmtl;
}
/**
* html -> markdown;
* @param $html
* @return string
*/
public function htmlToMarkdown($html)
{
$converter = new HtmlConverter(['header_style' => 'atx']);
$converter->getConfig()->setOption('list_item_style', '*');
return $converter->convert($html);
}
}
namespace App\Http\Controllers\Traits;
use League\HTMLToMarkdown\HtmlConverter;
trait Markdown
{
/**
* markdown -> html
* @param $markdown
* @return mixed
*/
public function markdownToHtml($markdown)
{
// markdown to html
$convertedHmtl = app('Parsedown')->setBreaksEnabled(true)->text($markdown);
/** XSS 防注入 */
$convertedHmtl = clean($convertedHmtl, 'markdown');
// 代码高亮展示优化
$convertedHmtl = str_replace("<pre><code>", '<pre><code class=" language-php">', $convertedHmtl);
// 移除 {{}}
// $convertedHmtl = remove_vue($convertedHmtl);
// 返回 html
return $convertedHmtl;
}
/**
* html -> markdown;
* @param $html
* @return string
*/
public function htmlToMarkdown($html)
{
$converter = new HtmlConverter(['header_style' => 'atx']);
$converter->getConfig()->setOption('list_item_style', '*');
return $converter->convert($html);
}
}
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Traits\Markdown;
class ArticlesController extends Controller{
use Markdown;
public function show(Article $article)
{
// 转换markdown
$article->body = $this->markdownToHtml($article->body);
return view('pages.articles.show', compact('article'));
}
}
上一篇:随机生成名字 下一篇:php使用xpath来进行采集页面的内容