Process Markdown `<pre><code>` blocks.
@param  string $text
@return string
347307
protected function doCodeBlocks($text) {
		$text = preg_replace_callback('{
				(?:\n\n|\A\n?)
				(	            # $1 = the code block -- one or more lines, starting with a space/tab
				  (?>
					[ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
					.*\n+
				  )+
				)
				((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
			}xm',
			array($this, '_doCodeBlocks_callback'), $text);

		return $text;
	}
481309
public static function processMarkdown($string, $block = true)
    {
        $page     = Grav::instance()['page'] ?? null;
        $defaults = Grav::instance()['config']->get('system.pages.markdown');

        // Initialize the preferred variant of Parsedown
        if ($defaults['extra']) {
            $parsedown = new ParsedownExtra($page, $defaults);
        } else {
            $parsedown = new Parsedown($page, $defaults);
        }

        if ($block) {
            $string = $parsedown->text($string);
        } else {
            $string = $parsedown->line($string);
        }

        return $string;
    }
998213
public function format(string $text) : string
    {
        if ($text === '') {
            return $text;
        }

        $startCodes = [];
        $endCodes = [];

        if ($this->foregroundColor !== null) {
            $startCodes[] = self::$supportedForegroundColors[$this->foregroundColor][0];
            $endCodes[] = self::$supportedForegroundColors[$this->foregroundColor][1];
        }

        if ($this->backgroundColor !== null) {
            $startCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][0];
            $endCodes[] = self::$supportedBackgroundColors[$this->backgroundColor][1];
        }

        foreach ($this->textStyles as $style) {
            $startCodes[] = self::$supportedTextStyles[$style][0];
            $endCodes[] = self::$supportedTextStyles[$style][1];
        }

        if (count($startCodes) === 0 && count($endCodes) === 0) {
            // No point in trying to format the text
            return $text;
        }

        return sprintf(
            "\033[%sm%s\033[%sm",
            implode(';', $startCodes),
            $text,
            implode(';', $endCodes)
        );
    }
515011
protected function processInline($text)
    {
        while ($text) {
            if (preg_match(self::MATCH_LINK, $text, $m)) {
                return $this->processLink($m[1], $m[2], $m[3], $m[4]);
            }

            $importantTextAhead = $this->lookAhead($text, self::STRONG_START_END);
            $emphasizedTextAhead = $this->lookAhead($text, self::EMPHASIZED_START_END);

            if ($importantTextAhead === false) {
                $importantTextAhead = $this->lookAhead($text, self::STRONG_START_END_TYPE_2);
            }

            if ($emphasizedTextAhead === false) {
                $emphasizedTextAhead = $this->lookAhead($text, self::EMPHASIZED_START_END_TYPE_2);
            }

            if ($importantTextAhead !== false && $emphasizedTextAhead !== false) {
                if ($importantTextAhead <= $emphasizedTextAhead) {
                    $unformattedText = mb_substr($text, 0, $importantTextAhead);
                    $importantText = mb_substr($text, $importantTextAhead);
                    $this->text($unformattedText);

                    return $this->processStrong($importantText);
                } else {
                    $unformattedText = mb_substr($text, 0, $emphasizedTextAhead);
                    $emphasizedText = mb_substr($text, $emphasizedTextAhead);
                    $this->text($unformattedText);

                    return $this->processEmphasized($emphasizedText);
                }
            } elseif ($importantTextAhead !== false) {
                $unformattedText = mb_substr($text, 0, $importantTextAhead);
                $importantText = mb_substr($text, $importantTextAhead);
                $this->text($unformattedText);

                return $this->processStrong($importantText);
            } elseif ($emphasizedTextAhead !== false) {
                $unformattedText = mb_substr($text, 0, $emphasizedTextAhead);
                $emphasizedText = mb_substr($text, $emphasizedTextAhead);
                $this->text($unformattedText);

                return $this->processEmphasized($emphasizedText);
            }

            $text = $this->processRestOfLine($text);
        };

        return ''; //All text is consumed
    }
364541
public function removeShortcodeTags($text)
    {
        $contentHandler = function (ShortcodeInterface $s) {
            return $s->getContent();
        };

        return $this->createShortcodeProcessor($contentHandler)->process($text);
    }
1313010
protected function sanitize_text( $text ) {
		// not fancy
		$text = strip_tags( $text );
		$text = esc_html( $text );
		$text = trim( $text );

		return $text;
	}
1209446
protected function parse_markdown( $text ) {
		static $markdown = null;

		if ( null === $markdown ) {
			$markdown = new Parsedown();
		}

		return $markdown->text( $text );
	}
1223015
private function parseInlineHtml($text)
	{
		if (strpos($text, '>') !== false) {
			// convert a name markers to \labels
			if (preg_match('~^<((a|span)) (name|id)="(.*?)">.*?</\1>~i', $text, $matches)) {
				return [
					['label', 'name' => str_replace('#', '::', $this->labelPrefix . $matches[4])],
					strlen($matches[0])
				];
			}
		}
		return [['text', '<'], 1];
	}
1294797
public function apply($text)
    {
        $foreground = null;
        $background = null;

        if($this->foreground)
            $foreground = 'color: ' . $this->foreground . ';';

        if($this->background)
            $background = 'background: ' . $this->background . ';';

        $dom = '<span style="'.$foreground.$background.'">' . $text . '</span>';

        return $dom;
    }
653466
private static function countCode($text)
    {
        // remove code attribute content, like from href="" or d=""
        $text = preg_replace('/"[^"]*"/i', '', $text);
        // get markdown code
        $regex = '/(?<=(?<!`))`([^`\n\r]+)`(?=(?!`))|```[a-zA-Z]*([^`]*)```/i';
        $markdownCount = preg_match_all($regex, $text, $markdownMatches, PREG_PATTERN_ORDER);
        // Remove markdown code from text, as to not double count
        $text = trim(preg_replace('/(?<=(?<!`))`[^`\n\r]+`(?=(?!`))|```[a-zA-Z]*[^`]*```/i', ' ', $text));

        // get html code elements
        $regex = '/<code>([\s\S]*?)<\/code>/i';
        $htmlCount = preg_match_all($regex, $text, $htmlMatches, PREG_PATTERN_ORDER);

        // check if any matches exist
        if ($markdownCount === 0 && $htmlCount === 0) {
            return 0;
        }
        // concat all code
        $code = implode($markdownMatches[1], ' ').' '.implode($markdownMatches[2], ' ').' '.implode($htmlMatches[1], ' ');

        // replace multiple spaces
        $code = preg_replace(['/\s+/', '/^\s/'], [' ', ''], $code);

        // return the number words in the code blocks
        return count(array_filter(explode(' ', $code)));
    }
455952
public function shortCode($text)
    {
        $patterns = [
            '/\[(FIGURE)[\s+](.+)\]/',
            '/\[(BASEURL)\]/',
            '/\[(RELURL)\]/',
            '/\[(ASSET)\]/',
        ];

        return preg_replace_callback(
            $patterns,
            function ($matches) {
                switch ($matches[1]) {

                    case 'FIGURE':
                        return CTextFilter::shortCodeFigure($matches[2]);
                        break;

                    case 'BASEURL':
                        return CTextFilter::shortCodeBaseurl();
                        break;

                    case 'RELURL':
                        return CTextFilter::shortCodeRelurl();
                        break;

                    case 'ASSET':
                        return CTextFilter::shortCodeAsset();
                        break;

                    default:
                        return "{$matches[1]} is unknown shortcode.";
                }
            },
            $text
        );
    }
393865
protected function renderText($text)
	{
		if ($this->enableNewlines) {
			return preg_replace("/(  \n|\n)/", "\\\\\\\\\n", $this->escapeLatex($text[1]));
		} else {
			return parent::renderText($text);
		}
	}
893828
protected function _processText($text)
    {
        $matches = array();

        preg_match_all("/(href|src)=\"(?!http|ftp|https|mailto|data)([^\"]*)\"/", $text, $matches, PREG_SET_ORDER);

        foreach ($matches as $match)
        {
            $route = $this->getObject('lib:dispatcher.router.route', array(
                'url'    => $match[2],
                'escape' => false
            ));

            //Add the host and the schema
            $route->scheme = $this->getUrl()->scheme;
            $route->host   = $this->getUrl()->host;

            $text = str_replace($match[0], $match[1].'="'.$route.'"', $text);
        }

        return $text;
    }
24676
protected function format_text($text) {
        // Since we allow output for highlighting, we need to encode html entities.
        // This ensures plaintext html chars don't become valid html.
        $out = s($text);

        $startcount = 0;
        $endcount = 0;

        // Remove end/start pairs that span a few common seperation characters. Allows us to highlight phrases instead of words.
        $regex = '|'.engine::HIGHLIGHT_END.'([ .,-]{0,3})'.engine::HIGHLIGHT_START.'|';
        $out = preg_replace($regex, '$1', $out);

        // Now replace our start and end highlight markers.
        $out = str_replace(engine::HIGHLIGHT_START, '<span class="highlight">', $out, $startcount);
        $out = str_replace(engine::HIGHLIGHT_END, '</span>', $out, $endcount);

        // This makes sure any highlight tags are balanced, incase truncation or the highlight text contained our markers.
        while ($startcount > $endcount) {
            $out .= '</span>';
            $endcount++;
        }
        while ($startcount < $endcount) {
            $out = '<span class="highlight">' . $out;
            $endcount++;
        }

        return parent::format_text($out);
    }
887626
public static function textPreprocess($text, $params)
    {
        // translate '{{PARAM}}'
        $trtab = [];
        if (is_array($params)) {
            foreach ((array)$params as $name => $value) {
                $trtab['{{' . $name . '}}'] = $value;
            }
            $text = strtr($text, $trtab);
        }

        // find and process in text '{{%plugin ...params...}}'
        $text = preg_replace_callback('/{{%([^}]+)}}/', 'static::runPlugin', $text);
        
        // erase other '{{...}}'
        $text = preg_replace('/{{[^}]*}}/', '', $text);
        return $text;
    }
847971
static private function borkify( $text )
    {
        $textBlocks = preg_split( '/(%[^ ]+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
        $newTextBlocks = array();
        foreach ( $textBlocks as $text )
        {
            if ( strlen( $text ) && $text[0] == '%' )
            {
                $newTextBlocks[] = (string) $text;
                continue;
            }

            $orgtext = $text;

            $searchMap = array(
                '/au/', '/\Bu/', '/\Btion/', '/an/', '/a\B/', '/en\b/',
                '/\Bew/', '/\Bf/', '/\Bir/', '/\Bi/', '/\bo/', '/ow/', '/ph/',
                '/th\b/', '/\bU/', '/y\b/', '/v/', '/w/', '/ooo/',
            );
            $replaceMap = array(
                'oo', 'oo', 'shun', 'un', 'e', 'ee',
                'oo', 'ff', 'ur', 'ee', 'oo', 'oo', 'f',
                't', 'Oo', 'ai', 'f', 'v', 'oo',
            );
            $text = preg_replace( $searchMap, $replaceMap, $text );

            if ( $orgtext == $text && count( $newTextBlocks ) )
            {
                $text .= '-a';
            }
            $newTextBlocks[] = (string) $text;
        }
        $text = implode( '', $newTextBlocks );
        $text = preg_replace( '/([:.?!])(.*)/', '\\2\\1', $text );
        return "[$text]";
    }
866405
static function strtolower( $text )
    {
        //We need to detect our internal charset
        if ( self::$charset === null )
        {
            self::$charset = eZTextCodec::internalCharset();
        }

        //First try to use mbstring
        if ( extension_loaded( 'mbstring' ) )
        {
            return mb_strtolower( $text, self::$charset );
        }
        else
        {
            // Fall back if mbstring is not available
            $char = eZCharTransform::instance();
            return $char->transformByGroup( $text, 'lowercase' );
        }
    }