Markdown.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Tools;
  3. use Illuminate\Support\Str;
  4. class Markdown
  5. {
  6. public static function driver($driver)
  7. {
  8. $GLOBALS['markdown.driver'] = $driver;
  9. }
  10. public static function render($text)
  11. {
  12. return Markdown::strMarkdown($text);
  13. }
  14. public static function strMarkdown($text)
  15. {
  16. $text = str_replace("** ", "**\r\n ", $text);
  17. $html = Str::markdown($text);
  18. $html = self::replaceSinglePWithSpan($html);
  19. return $html;
  20. }
  21. /**
  22. * 如果字符串中只有一对 p 标签,则替换为 span
  23. *
  24. * @param string $html
  25. * @return string
  26. */
  27. public static function replaceSinglePWithSpan(string $html): string
  28. {
  29. // 先过滤掉只含空白/全角空格的 <p>
  30. $html = preg_replace('/<p\b[^>]*>[\s ]*<\/p>/u', '', $html);
  31. $html = trim($html);
  32. preg_match_all('/<p\b[^>]*>.*?<\/p>/is', $html, $matches);
  33. if (count($matches[0]) === 1) {
  34. return preg_replace(
  35. ['/^\s*<p\b([^>]*)>/i', '/<\/p>\s*$/i'],
  36. ['<span$1>', '</span>'],
  37. $html
  38. );
  39. }
  40. return $html;
  41. }
  42. }