EmphStrongTrait.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2014 Carsten Brandt
  4. * @license https://github.com/cebe/markdown/blob/master/LICENSE
  5. * @link https://github.com/cebe/markdown#readme
  6. */
  7. namespace cebe\markdown\inline;
  8. /**
  9. * Adds inline emphasizes and strong elements
  10. */
  11. trait EmphStrongTrait
  12. {
  13. /**
  14. * Parses empathized and strong elements.
  15. * @marker _
  16. * @marker *
  17. */
  18. protected function parseEmphStrong($text)
  19. {
  20. $marker = $text[0];
  21. if (!isset($text[1])) {
  22. return [['text', $text[0]], 1];
  23. }
  24. if ($marker == $text[1]) { // strong
  25. // work around a PHP bug that crashes with a segfault on too much regex backtrack
  26. // check whether the end marker exists in the text
  27. // https://github.com/erusev/parsedown/issues/443
  28. // https://bugs.php.net/bug.php?id=45735
  29. if (strpos($text, $marker . $marker, 2) === false) {
  30. return [['text', $text[0] . $text[1]], 2];
  31. }
  32. if ($marker == '*' && preg_match('/^[*]{2}((?:[^*]|[*][^*]*[*])+?)[*]{2}(?![*]{2})/s', $text, $matches) ||
  33. $marker == '_' && preg_match('/^__((?:[^_]|_[^_]*_)+?)__(?!__)/us', $text, $matches)) {
  34. return [
  35. [
  36. 'strong',
  37. $this->parseInline($matches[1]),
  38. ],
  39. strlen($matches[0])
  40. ];
  41. }
  42. } else { // emph
  43. // work around a PHP bug that crashes with a segfault on too much regex backtrack
  44. // check whether the end marker exists in the text
  45. // https://github.com/erusev/parsedown/issues/443
  46. // https://bugs.php.net/bug.php?id=45735
  47. if (strpos($text, $marker, 1) === false) {
  48. return [['text', $text[0]], 1];
  49. }
  50. if ($marker == '*' && preg_match('/^[*]((?:[^*]|[*][*][^*]+?[*][*])+?)[*](?![*][^*])/s', $text, $matches) ||
  51. $marker == '_' && preg_match('/^_((?:[^_]|__[^_]*__)+?)_(?!_[^_])\b/us', $text, $matches)) {
  52. return [
  53. [
  54. 'emph',
  55. $this->parseInline($matches[1]),
  56. ],
  57. strlen($matches[0])
  58. ];
  59. }
  60. }
  61. return [['text', $text[0]], 1];
  62. }
  63. protected function renderStrong($block)
  64. {
  65. return '<strong>' . $this->renderAbsy($block[1]) . '</strong>';
  66. }
  67. protected function renderEmph($block)
  68. {
  69. return '<em>' . $this->renderAbsy($block[1]) . '</em>';
  70. }
  71. }