3 namespace League\HTMLToMarkdown\Converter;
5 use League\HTMLToMarkdown\ElementInterface;
7 class PreformattedConverter implements ConverterInterface
10 * @param ElementInterface $element
14 public function convert(ElementInterface $element)
18 $pre_content = html_entity_decode($element->getChildrenAsString());
19 $pre_content = str_replace(array('<pre>', '</pre>'), '', $pre_content);
22 * Checking for the code tag.
23 * Usually pre tags are used along with code tags. This conditional will check for already converted code tags,
24 * which use backticks, and if those backticks are at the beginning and at the end of the string it means
25 * there's no more information to convert.
28 $firstBacktick = strpos(trim($pre_content), '`');
29 $lastBacktick = strrpos(trim($pre_content), '`');
30 if ($firstBacktick === 0 && $lastBacktick === strlen(trim($pre_content)) - 1) {
34 // If the execution reaches this point it means it's just a pre tag, with no code tag nested
36 // Normalizing new lines
37 $pre_content = preg_replace('/\r\n|\r|\n/', PHP_EOL, $pre_content);
39 // Checking if the string has multiple lines
40 $lines = preg_split('/\r\n|\r|\n/', $pre_content);
41 if (count($lines) > 1) {
42 // Multiple lines detected, adding three backticks and newlines
43 $markdown .= '```' . "\n" . $pre_content . "\n" . '```';
45 // One line of code, wrapping it on one backtick.
46 $markdown .= '`' . $pre_content . '`';
55 public function getSupportedTags()