Markdown.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. preg_match_all('/<p\b[^>]*>.*?<\/p>/is', $html, $matches);
  30. if (count($matches[0]) === 1) {
  31. return preg_replace(
  32. ['/^\s*<p\b([^>]*)>/i', '/<\/p>\s*$/i'],
  33. ['<span$1>', '</span>'],
  34. $html
  35. );
  36. }
  37. return $html;
  38. }
  39. }