首页 > 代码库 > laravel 中引入markdown,html处理插件
laravel 中引入markdown,html处理插件
1.Purifier:过滤不良的代码插件
composer 中引入 ,git地址
"mews/purifier": "~2.0"
php artisan vendor:publish --provider="Mews\Purifier\PurifierServiceProvider"
2.引入html转markdown插件,git地址
"league/html-to-markdown": "^4.2",
3.引入markdown转html插件,git地址 官网地址
"erusev/parsedown": "^1.6",
4.测试代码
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\Mention; use Parsedown; use League\HTMLToMarkdown\HtmlConverter; use Purifier; class Test extends Controller { protected $htmlParser; protected $markdownParser; public function __construct() { $this->htmlParser = new HtmlConverter([‘header_style‘ => ‘atx‘]); $this->markdownParser = new Parsedown(); } public function t2(Request $request) { $mention = new Mention(); $content = $request->input(‘content‘); $markdownContent = $mention->parse($content); $htmlContent = $this->convertMarkdownToHtml($markdownContent); var_dump($htmlContent);exit; } public function convertHtmlToMarkdown($html) { return $this->htmlParser->convert($html); } public function convertMarkdownToHtml($markdown) { $convertedHmtl = $this->markdownParser->setBreaksEnabled(true)->text($markdown); $convertedHmtl = Purifier::clean($convertedHmtl, ‘user_topic_body‘); $convertedHmtl = str_replace("<pre><code>", ‘<pre><code class=" language-php">‘, $convertedHmtl); return $convertedHmtl; } }
mention 类文件代码
<?php namespace App\Services; use App\Model\User; class Mention { public $body_parsed; public $users = []; public $usernames; public $body_original; public function getMentionedUsername() { preg_match_all("/(\S*)\@([^\r\n\s]*)/i", $this->body_original, $atlist_tmp); $usernames = []; foreach ($atlist_tmp[2] as $k=>$v) { if ($atlist_tmp[1][$k] || strlen($v) >25) { continue; } $usernames[] = $v; } return array_unique($usernames); } public function replace() { $this->body_parsed = $this->body_original; foreach ($this->users as $user) { $search = ‘@‘ . $user->name; //$place = ‘[‘.$search.‘](‘.route(‘users.show‘, $user->id).‘)‘; $place = ‘[‘.$search.‘](http://user?id=‘.$user->id.‘)‘; $this->body_parsed = str_replace($search, $place, $this->body_parsed); } } public function parse($body) { $this->body_original = $body; $this->usernames = $this->getMentionedUsername(); count($this->usernames) > 0 && $this->users = User::whereIn(‘name‘, $this->usernames)->get(); $this->replace(); return $this->body_parsed; } }
laravel 中引入markdown,html处理插件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。