3 namespace League\HTMLToMarkdown\Converter;
5 use League\HTMLToMarkdown\ElementInterface;
7 class CodeConverter implements ConverterInterface
10 * @param ElementInterface $element
14 public function convert(ElementInterface $element)
18 // Checking for language class on the code block
19 $classes = $element->getAttribute('class');
22 // Since tags can have more than one class, we need to find the one that starts with 'language-'
23 $classes = explode(' ', $classes);
24 foreach ($classes as $class) {
25 if (strpos($class, 'language-') !== false) {
26 // Found one, save it as the selected language and stop looping over the classes.
27 // The space after the language avoids gluing the actual code with the language tag
28 $language = str_replace('language-', '', $class) . ' ';
35 $code = html_entity_decode($element->getChildrenAsString());
37 // In order to remove the code tags we need to search for them and, in the case of the opening tag
38 // use a regular expression to find the tag and the other attributes it might have
39 $code = preg_replace('/<code\b[^>]*>/', '', $code);
40 $code = str_replace('</code>', '', $code);
42 // Checking if the code has multiple lines
43 $lines = preg_split('/\r\n|\r|\n/', $code);
44 if (count($lines) > 1) {
45 // Multiple lines detected, adding three backticks and newlines
46 $markdown .= '```' . $language . "\n" . $code . "\n" . '```';
48 // One line of code, wrapping it on one backtick.
49 $markdown .= '`' . $language . $code . '`';
58 public function getSupportedTags()