MdRender.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. <?php
  2. namespace App\Http\Api;
  3. use App\Models\Channel;
  4. use App\Tools\Markdown;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Str;
  7. // use App\Services\TemplateRender;
  8. define('STACK_DEEP', 8);
  9. class MdRender
  10. {
  11. /**
  12. * 文字渲染模式
  13. * read 阅读模式
  14. * edit 编辑模式
  15. */
  16. protected $options = [
  17. 'mode' => 'read',
  18. 'channelType' => 'translation',
  19. 'contentType' => 'markdown',
  20. 'format' => 'react',
  21. 'debug' => [],
  22. 'studioId' => null,
  23. 'lang' => 'zh-Hans',
  24. 'footnote' => false,
  25. 'paragraph' => false,
  26. ];
  27. public function __construct($options = [])
  28. {
  29. foreach ($options as $key => $value) {
  30. $this->options[$key] = $value;
  31. }
  32. }
  33. /**
  34. * 将句子模版组成的段落复制一份,为了实现巴汉逐段对读
  35. */
  36. private function preprocessingForParagraph($input)
  37. {
  38. if (! $this->options['paragraph']) {
  39. return $input;
  40. }
  41. $paragraphs = explode("\n\n", $input);
  42. $output = [];
  43. foreach ($paragraphs as $key => $paragraph) {
  44. // 判断是否是纯粹的句子模版
  45. $pattern = "/\{\{sent\|id=([0-9].+?)\}\}/";
  46. $replacement = '';
  47. $space = preg_replace($pattern, $replacement, $paragraph);
  48. $space = str_replace('>', '', $space);
  49. if (empty(trim($space))) {
  50. $output[] = str_replace('}}', '|text=origin}}', $paragraph);
  51. $output[] = str_replace('}}', '|text=translation}}', $paragraph);
  52. } else {
  53. $output[] = $paragraph;
  54. }
  55. }
  56. return implode("\n\n", $output);
  57. }
  58. /**
  59. * 按照{{}}把字符串切分成三个部分。模版之前的,模版,和模版之后的
  60. */
  61. private function tplSplit($tpl)
  62. {
  63. $before = strpos($tpl, '{{');
  64. if ($before === false) {
  65. // 未找到
  66. return ['data' => [$tpl, '', ''], 'error' => 0];
  67. } else {
  68. $pointer = $before;
  69. $stack = [];
  70. $stack[] = $pointer;
  71. $after = substr($tpl, $pointer + 2);
  72. while (! empty($after) && count($stack) > 0 && count($stack) < STACK_DEEP) {
  73. $nextBegin = strpos($after, '{{');
  74. $nextEnd = strpos($after, '}}');
  75. if ($nextBegin !== false) {
  76. if ($nextBegin < $nextEnd) {
  77. // 有嵌套找到最后一个}}
  78. $pointer = $pointer + 2 + $nextBegin;
  79. $stack[] = $pointer;
  80. $after = substr($tpl, $pointer + 2);
  81. } elseif ($nextEnd !== false) {
  82. // 无嵌套有结束
  83. $pointer = $pointer + 2 + $nextEnd;
  84. array_pop($stack);
  85. $after = substr($tpl, $pointer + 2);
  86. } else {
  87. // 无结束符 没找到
  88. break;
  89. }
  90. } elseif ($nextEnd !== false) {
  91. $pointer = $pointer + 2 + $nextEnd;
  92. array_pop($stack);
  93. $after = substr($tpl, $pointer + 2);
  94. } else {
  95. // 没找到
  96. break;
  97. }
  98. }
  99. if (count($stack) > 0) {
  100. if (count($stack) === STACK_DEEP) {
  101. return ['data' => [$tpl, '', ''], 'error' => 2];
  102. } else {
  103. // 未关闭
  104. return ['data' => [$tpl, '', ''], 'error' => 1];
  105. }
  106. } else {
  107. return [
  108. 'data' => [
  109. substr($tpl, 0, $before),
  110. substr($tpl, $before, $pointer - $before + 2),
  111. substr($tpl, $pointer + 2),
  112. ],
  113. 'error' => 0,
  114. ];
  115. }
  116. }
  117. }
  118. private function wiki2xml(string $wiki, $channelId = []): string
  119. {
  120. /**
  121. * 渲染markdown里面的模版
  122. */
  123. $remain = $wiki;
  124. $buffer = [];
  125. do {
  126. $arrWiki = $this->tplSplit($remain);
  127. $buffer[] = $arrWiki['data'][0];
  128. $tpl = $arrWiki['data'][1];
  129. if (! empty($tpl)) {
  130. /**
  131. * 处理模版 提取参数
  132. */
  133. $tpl = str_replace("|\n", '|', $tpl);
  134. $pattern = "/\{\{(.+?)\|/";
  135. $replacement = '<MdTpl class="tpl" name="$1"><param>';
  136. $tpl = preg_replace($pattern, $replacement, $tpl);
  137. $tpl = str_replace('}}', '</param></MdTpl>', $tpl);
  138. $tpl = str_replace('|', '</param><param>', $tpl);
  139. /**
  140. * 替换变量名
  141. */
  142. $pattern = '/<param>([a-z]+?)=/';
  143. $replacement = '<param name="$1">';
  144. $tpl = preg_replace($pattern, $replacement, $tpl);
  145. // tpl to react
  146. $tpl = str_replace('<param', '<span class="param"', $tpl);
  147. $tpl = str_replace('</param>', '</span>', $tpl);
  148. $tpl = $this->xml2tpl($tpl, $channelId);
  149. $buffer[] = $tpl;
  150. }
  151. $remain = $arrWiki['data'][2];
  152. } while (! empty($remain));
  153. $html = implode('', $buffer);
  154. return $html;
  155. }
  156. private function xmlQueryId(string $xml, string $id): string
  157. {
  158. try {
  159. $dom = simplexml_load_string($xml);
  160. } catch (\Exception $e) {
  161. Log::error($e);
  162. return '<div></div>';
  163. }
  164. $tpl_list = $dom->xpath('//MdTpl');
  165. foreach ($tpl_list as $key => $tpl) {
  166. foreach ($tpl->children() as $param) {
  167. // 处理每个参数
  168. if ($param->getName() === 'param') {
  169. foreach ($param->attributes() as $pa => $pa_value) {
  170. $pValue = $pa_value->__toString();
  171. if ($pa === 'name' && $pValue === 'id') {
  172. if ($param->__toString() === $id) {
  173. return $tpl->asXML();
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. return '<div></div>';
  181. }
  182. public static function take_sentence(string $xml): array
  183. {
  184. $output = [];
  185. try {
  186. $dom = simplexml_load_string($xml);
  187. } catch (\Exception $e) {
  188. Log::error($e);
  189. return $output;
  190. }
  191. $tpl_list = $dom->xpath('//MdTpl');
  192. foreach ($tpl_list as $key => $tpl) {
  193. foreach ($tpl->attributes() as $a => $a_value) {
  194. if ($a === 'name') {
  195. if ($a_value->__toString() === 'sent') {
  196. foreach ($tpl->children() as $param) {
  197. // 处理每个参数
  198. if ($param->getName() === 'param') {
  199. $sent = $param->__toString();
  200. if (! empty($sent)) {
  201. $output[] = $sent;
  202. break;
  203. }
  204. }
  205. }
  206. }
  207. }
  208. }
  209. }
  210. return $output;
  211. }
  212. private function xml2tpl(string $xml, $channelId = []): string
  213. {
  214. /**
  215. * 解析xml
  216. * 获取模版参数
  217. * 生成react 组件参数
  218. */
  219. try {
  220. // $dom = simplexml_load_string($xml);
  221. $doc = new \DOMDocument;
  222. $xml = str_replace('MdTpl', 'dfn', $xml);
  223. $xml = mb_convert_encoding($xml, 'HTML-ENTITIES', 'UTF-8');
  224. $ok = $doc->loadHTML($xml, LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  225. } catch (\Exception $e) {
  226. Log::error($e);
  227. Log::error($xml);
  228. return "<span>xml解析错误{$e}</span>";
  229. }
  230. if (! $ok) {
  231. return '<span>xml解析错误</span>';
  232. }
  233. /*
  234. if(!$dom){
  235. Log::error($xml);
  236. return "<span>xml解析错误</span>";
  237. }
  238. */
  239. $tpl_list = $doc->getElementsByTagName('dfn');
  240. foreach ($tpl_list as $key => $tpl) {
  241. /**
  242. * 遍历 MdTpl 处理参数
  243. */
  244. $props = [];
  245. $tpl_name = '';
  246. foreach ($tpl->attributes as $a => $a_value) {
  247. if ($a_value->nodeName === 'name') {
  248. $tpl_name = $a_value->nodeValue;
  249. break;
  250. }
  251. }
  252. $param_id = 0;
  253. $child = $tpl->firstChild;
  254. while ($child) {
  255. // 处理每个参数
  256. if ($child->nodeName === 'span') {
  257. $param_id++;
  258. $paramName = '';
  259. foreach ($child->attributes as $pa => $pa_value) {
  260. if ($pa_value->nodeName === 'name') {
  261. $nodeText = $pa_value->nodeValue;
  262. $props["{$nodeText}"] = $child->nodeValue;
  263. $paramName = $pa_value;
  264. }
  265. }
  266. if (empty($paramName)) {
  267. foreach ($child->childNodes as $param_child) {
  268. // code...
  269. if ($param_child->nodeType === 3) {
  270. $props["{$param_id}"] = $param_child->nodeValue;
  271. }
  272. }
  273. }
  274. }
  275. $child = $child->nextSibling;
  276. }
  277. /**
  278. * 生成模版参数
  279. */
  280. $channelInfo = [];
  281. foreach ($channelId as $key => $id) {
  282. if (Str::isUuid($id)) {
  283. $channelInfo[] = Channel::where('uid', $id)->first();
  284. }
  285. }
  286. $tplRender = new TemplateRender(
  287. $props,
  288. $channelInfo,
  289. $this->options['mode'],
  290. $this->options['format'],
  291. $this->options['studioId'],
  292. $this->options['debug'],
  293. $this->options['lang'],
  294. );
  295. $tplRender->options($this->options);
  296. $tplProps = $tplRender->render($tpl_name);
  297. /*
  298. $tplProps = TemplateRender::name($tpl_name)
  299. ->options($this->options)
  300. ->param($props)
  301. ->render();
  302. */
  303. if ($this->options['format'] === 'react' && $tplProps) {
  304. $props = $doc->createAttribute('props');
  305. $props->nodeValue = $tplProps['props'];
  306. $tpl->appendChild($props);
  307. $attTpl = $doc->createAttribute('tpl');
  308. $attTpl->nodeValue = $tplProps['tpl'];
  309. $tpl->appendChild($attTpl);
  310. $htmlElement = $doc->createElement($tplProps['tag']);
  311. $htmlElement->nodeValue = $tplProps['html'];
  312. $tpl->appendChild($htmlElement);
  313. }
  314. }
  315. $html = $doc->saveHTML();
  316. $html = str_replace(['<dfn', '</dfn>'], ['<MdTpl', '</MdTpl>'], $html);
  317. switch ($this->options['format']) {
  318. case 'react':
  319. return trim($html);
  320. break;
  321. case 'unity':
  322. if (isset($tplProps) && is_array($tplProps)) {
  323. return '{{'."{$tplProps['tpl']}|{$tplProps['props']}".'}}';
  324. } else {
  325. return '';
  326. }
  327. break;
  328. default:
  329. /**html tex text simple markdown */
  330. if (isset($tplProps)) {
  331. if (is_array($tplProps)) {
  332. if (isset($tplProps[0])) {
  333. return $tplProps[0];
  334. } else {
  335. return '';
  336. }
  337. } else {
  338. return $tplProps;
  339. }
  340. } else {
  341. Log::error('tplProps undefine');
  342. return '';
  343. }
  344. break;
  345. }
  346. }
  347. /**
  348. * 将markdown文件中的模版转换为标准的wiki模版
  349. */
  350. private function markdown2wiki(string $markdown): string
  351. {
  352. // $markdown = mb_convert_encoding($markdown,'UTF-8','UTF-8');
  353. $markdown = iconv('UTF-8', 'UTF-8//IGNORE', $markdown);
  354. /**
  355. * nissaya
  356. * aaa=bbb\n
  357. * {{nissaya|aaa|bbb}}
  358. */
  359. if ($this->options['channelType'] === 'nissaya') {
  360. if ($this->options['contentType'] === 'json') {
  361. $json = json_decode($markdown);
  362. $nissayaWord = [];
  363. if (is_array($json)) {
  364. foreach ($json as $word) {
  365. if (count($word->sn) === 1) {
  366. // 只输出第一层级
  367. $str = '{{nissaya|';
  368. if (isset($word->word->value)) {
  369. $str .= $word->word->value;
  370. }
  371. $str .= '|';
  372. if (isset($word->meaning->value)) {
  373. $str .= $word->meaning->value;
  374. }
  375. $str .= '}}';
  376. $nissayaWord[] = $str;
  377. }
  378. }
  379. } else {
  380. Log::error('json data is not array', ['data' => $markdown]);
  381. }
  382. $markdown = implode('', $nissayaWord);
  383. } elseif ($this->options['contentType'] === 'markdown') {
  384. $lines = explode("\n", $markdown);
  385. $newLines = [];
  386. foreach ($lines as $line) {
  387. if (
  388. strstr($line, '=') === false &&
  389. strstr($line, '$') === false
  390. ) {
  391. $newLines[] = $line;
  392. } else {
  393. $line = str_replace('$', '=', $line);
  394. $nissaya = explode('=', $line);
  395. $meaning = array_slice($nissaya, 1);
  396. $meaning = implode('=', $meaning);
  397. $newLines[] = "{{nissaya|{$nissaya[0]}|{$meaning}}}";
  398. }
  399. }
  400. $markdown = implode("\n", $newLines);
  401. }
  402. }
  403. // $markdown = preg_replace("/\n\n/","<div></div>",$markdown);
  404. /**
  405. * 处理 mermaid
  406. */
  407. if (strpos($markdown, '```mermaid') !== false) {
  408. $lines = explode("\n", $markdown);
  409. $newLines = [];
  410. $mermaidBegin = false;
  411. $mermaidString = [];
  412. foreach ($lines as $line) {
  413. if ($line === '```mermaid') {
  414. $mermaidBegin = true;
  415. $mermaidString = [];
  416. continue;
  417. }
  418. if ($mermaidBegin) {
  419. if ($line === '```') {
  420. $newLines[] = '{{mermaid|'.base64_encode(\json_encode($mermaidString)).'}}';
  421. $mermaidBegin = false;
  422. } else {
  423. $mermaidString[] = $line;
  424. }
  425. } else {
  426. $newLines[] = $line;
  427. }
  428. }
  429. $markdown = implode("\n", $newLines);
  430. }
  431. /**
  432. * 替换换行符
  433. * react 无法处理 <br> 替换为<div></div>代替换行符作用
  434. */
  435. // $markdown = str_replace('<br>','<div></div>',$markdown);
  436. /**
  437. * markdown -> html
  438. */
  439. /*
  440. $html = MdRender::fixHtml($html);
  441. */
  442. // 替换术语
  443. $pattern = "/\[\[(.+?)\]\]/";
  444. $replacement = '{{term|$1}}';
  445. $markdown = preg_replace($pattern, $replacement, $markdown);
  446. // 替换句子模版
  447. $pattern = "/\{\{([0-9].+?)\}\}/";
  448. $replacement = '{{sent|id=$1}}';
  449. $markdown = preg_replace($pattern, $replacement, $markdown);
  450. /**
  451. * 替换多行注释
  452. * ```
  453. * bla
  454. * bla
  455. * ```
  456. * {{note|
  457. * bla
  458. * bla
  459. * }}
  460. */
  461. if (strpos($markdown, "```\n") !== false) {
  462. $lines = explode("\n", $markdown);
  463. $newLines = [];
  464. $noteBegin = false;
  465. $noteString = [];
  466. foreach ($lines as $line) {
  467. if ($noteBegin) {
  468. if ($line === '```') {
  469. $newLines[] = '}}';
  470. $noteBegin = false;
  471. } else {
  472. $newLines[] = $line;
  473. }
  474. } else {
  475. if ($line === '```') {
  476. $noteBegin = true;
  477. $newLines[] = '{{note|';
  478. continue;
  479. } else {
  480. $newLines[] = $line;
  481. }
  482. }
  483. }
  484. if ($noteBegin) {
  485. $newLines[] = '}}';
  486. }
  487. $markdown = implode("\n", $newLines);
  488. }
  489. /**
  490. * 替换单行注释
  491. * `bla bla`
  492. * {{note|bla}}
  493. */
  494. $pattern = '/`(.+?)`/';
  495. $replacement = '{{note|$1}}';
  496. $markdown = preg_replace($pattern, $replacement, $markdown);
  497. return $markdown;
  498. }
  499. private function markdownToHtml($markdown)
  500. {
  501. $markdown = str_replace('MdTpl', 'mdtpl', $markdown);
  502. $markdown = str_replace(['<param', '</param>'], ['<span', '</span>'], $markdown);
  503. $html = Markdown::render($markdown);
  504. if ($this->options['format'] === 'react') {
  505. $html = $this->fixHtml($html);
  506. }
  507. $html = str_replace('<hr>', '<hr />', $html);
  508. // 给H1-6 添加uuid
  509. for ($i = 1; $i < 7; $i++) {
  510. if (strpos($html, "<h{$i}>") === false) {
  511. continue;
  512. }
  513. $output = [];
  514. $input = $html;
  515. $hPos = strpos($input, "<h{$i}>");
  516. while ($hPos !== false) {
  517. $output[] = substr($input, 0, $hPos);
  518. $output[] = "<h{$i} id='".Str::uuid()."'>";
  519. $input = substr($input, $hPos + 4);
  520. $hPos = strpos($input, "<h{$i}>");
  521. }
  522. $output[] = $input;
  523. $html = implode('', $output);
  524. }
  525. $html = str_replace('mdtpl', 'MdTpl', $html);
  526. return $html;
  527. }
  528. private function fixHtml($html)
  529. {
  530. $doc = new \DOMDocument;
  531. libxml_use_internal_errors(true);
  532. $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
  533. $doc->loadHTML('<span>'.$html.'</span>', LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  534. $fixed = $doc->saveHTML();
  535. $fixed = mb_convert_encoding($fixed, 'UTF-8', 'HTML-ENTITIES');
  536. return $fixed;
  537. }
  538. public static function init()
  539. {
  540. $GLOBALS['MdRenderStack'] = 0;
  541. }
  542. public function convert($markdown, $channelId = [], $queryId = null)
  543. {
  544. if (isset($GLOBALS['MdRenderStack']) && is_numeric($GLOBALS['MdRenderStack'])) {
  545. $GLOBALS['MdRenderStack']++;
  546. } else {
  547. $GLOBALS['MdRenderStack'] = 1;
  548. }
  549. if ($GLOBALS['MdRenderStack'] < 3) {
  550. $output = $this->_convert($markdown, $channelId, $queryId);
  551. } else {
  552. $output = $markdown;
  553. }
  554. $GLOBALS['MdRenderStack']--;
  555. return $output;
  556. }
  557. private function _convert($markdown, $channelId = [], $queryId = null)
  558. {
  559. if (empty($markdown)) {
  560. switch ($this->options['format']) {
  561. case 'react':
  562. return '<span></span>';
  563. break;
  564. default:
  565. return '';
  566. break;
  567. }
  568. }
  569. $wiki = $this->markdown2wiki($markdown);
  570. $wiki = $this->preprocessingForParagraph($wiki);
  571. $markdownWithTpl = $this->wiki2xml($wiki, $channelId);
  572. if (! is_null($queryId)) {
  573. $html = $this->xmlQueryId($markdownWithTpl, $queryId);
  574. }
  575. $html = $this->markdownToHtml($markdownWithTpl);
  576. // 后期处理
  577. $output = '';
  578. switch ($this->options['format']) {
  579. case 'react':
  580. // 生成可展开组件
  581. $html = str_replace('<div/>', '<div></div>', $html);
  582. $pattern = '/<li><div>(.+?)<\/div><\/li>/';
  583. $replacement = '<li><MdTpl name="toggle" tpl="toggle" props=""><div>$1</div></MdTpl></li>';
  584. $output = preg_replace($pattern, $replacement, $html);
  585. break;
  586. case 'text':
  587. case 'simple':
  588. case 'prompt':
  589. $html = strip_tags($html);
  590. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  591. // $output = html_entity_decode($html);
  592. break;
  593. case 'tex':
  594. $html = strip_tags($html);
  595. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  596. // $output = html_entity_decode($html);
  597. break;
  598. case 'unity':
  599. $html = str_replace(['<strong>', '</strong>', '<em>', '</em>'], ['[%b%]', '[%/b%]', '[%i%]', '[%/i%]'], $html);
  600. $html = strip_tags($html);
  601. $html = str_replace(['[%b%]', '[%/b%]', '[%i%]', '[%/i%]'], ['<b>', '</b>', '<i>', '</i>'], $html);
  602. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  603. break;
  604. case 'html':
  605. $output = htmlspecialchars_decode($html, ENT_QUOTES);
  606. // 处理脚注
  607. if ($this->options['footnote'] && isset($GLOBALS['note']) && count($GLOBALS['note']) > 0) {
  608. $output .= '<div><h1>endnote</h1>';
  609. foreach ($GLOBALS['note'] as $footnote) {
  610. $output .= '<p><a name="footnote-'.$footnote['sn'].'">['.$footnote['sn'].']</a> '.$footnote['content'].'</p>';
  611. }
  612. $output .= '</div>';
  613. unset($GLOBALS['note']);
  614. }
  615. // 处理图片链接
  616. $output = str_replace('<img src="', '<img src="'.config('app.url'), $output);
  617. $output = $this->replaceSinglePWithSpan($output);
  618. break;
  619. case 'markdown':
  620. // 处理脚注
  621. $footnotes = [];
  622. if ($this->options['footnote'] && isset($GLOBALS['note']) && count($GLOBALS['note']) > 0) {
  623. foreach ($GLOBALS['note'] as $footnote) {
  624. $footnotes[] = '[^'.$footnote['sn'].']: '.$footnote['content'];
  625. }
  626. unset($GLOBALS['note']);
  627. }
  628. // 处理图片链接
  629. $output = str_replace('/attachments/', config('app.url').'/attachments/', $markdownWithTpl);
  630. $output = $output."\n\n".implode("\n\n", $footnotes);
  631. break;
  632. }
  633. return $output;
  634. }
  635. /**
  636. * string[] $channelId
  637. */
  638. public static function render($markdown, $channelId, $queryId = null, $mode = 'read', $channelType = 'translation', $contentType = 'markdown', $format = 'react')
  639. {
  640. $mdRender = new MdRender(
  641. [
  642. 'mode' => $mode,
  643. 'channelType' => $channelType,
  644. 'contentType' => $contentType,
  645. 'format' => $format,
  646. ]
  647. );
  648. $output = $mdRender->convert($markdown, $channelId, $queryId);
  649. return $output;
  650. }
  651. /**
  652. * 如果字符串中只有一对 p 标签,则替换为 span
  653. */
  654. public static function replaceSinglePWithSpan(string $html): string
  655. {
  656. preg_match_all('/<p\b[^>]*>.*?<\/p>/is', $html, $matches);
  657. if (count($matches[0]) === 1) {
  658. return preg_replace(
  659. ['/^\s*<p\b([^>]*)>/i', '/<\/p>\s*$/i'],
  660. ['<span$1>', '</span>'],
  661. $html
  662. );
  663. }
  664. return $html;
  665. }
  666. }