CTextHighlighter usage in blog

what is the best way to use CTextHighlighter

in blog posts?

like here for example ?


div and regexp?

Haven’t used the highlighter class, but you can use jQuery and div and id. :)

Or pre and code, like this one (which I am currently using):


It’s very unobtrusive.

I wrote this extension for another highlighter, SyntaxHighlighter by Alex Gorbatchev:


It’s also great.

thx for the answer… I familiar with the jQuery solutions…

I just curious how samdark doing it on his blog…

this is for sure CTextHighlighter work

for now I got something like

$string = '<div id="highlight">';

$string .= <<<CODE

test test3s gsdf gsdfg sdfg sd


$string .= '</div>';

$pattern = '/<div id="highlight">(.*)<\/div>/';

$replacement = '$1';

function test($matches)


  $hl = new CTextHighlighter();

  $hl->language = 'php';

  $hl->showLineNumbers = true;

  return $hl->highlight($matches[1]);


echo preg_replace_callback(




not perfect yet… just playing around…

I’m doing it using CMarkdownParser class.

The markdown parser does this for code:

	public function doFencedCodeBlocks($text) {


	# Adding the fenced code block syntax to regular Markdown:


	# ~~~

	# Code block

	# ~~~


		$less_than_tab = $this->tab_width;

		$text = preg_replace_callback('{


				# 1: Opening marker


					~{3,} # Marker: three tilde or more.


				[ ]* \n # Whitespace and newline following marker.

				# 2: Content



						(?!\1 [ ]* \n)	# Not a closing marker.




				# Closing marker.

				\1 [ ]* \n


			array(&$this, '_doFencedCodeBlocks_callback'), $text);

		return $text;


The CMarkdownParser does this:


	 * Callback function when a fenced code block is matched.

	 * @param array $matches matches

	 * @return string the highlighted code block


	public function _doFencedCodeBlocks_callback($matches)


		return "\n\n".$this->hashBlock($this->highlightCodeBlock($matches[2]))."\n\n";



	 * Highlights the code block.

	 * @param string $codeblock the code block

	 * @return string the highlighted code block. Null if the code block does not need to highlighted


	protected function highlightCodeBlock($codeblock)


		if(($tag=$this->getHighlightTag($codeblock))!==null && ($highlighter=$this->createHighLighter($tag)))


			$codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);

			$tagLen = strpos($codeblock, $tag)+strlen($tag);

			$codeblock = ltrim(substr($codeblock, $tagLen));

			$output=preg_replace('/<span\s+[^>]*>(\s*)<\/span>/', '\1', $highlighter->highlight($codeblock));

			return "<div class=\"{$this->highlightCssClass}\">".$output."</div>";



			return "<pre>".CHtml::encode($codeblock)."</pre>";


Thanks to both of you!

to make this complete for future searches… for markup you should include also the css