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; } }
时间: 2024-12-17 21:20:22