Preg_replace'ing a Preg_replace!

Hey gang,

Got a bit of a weird one here, to which I’m sure there is a simple answer.

On my new blog site, I’m implementing GeSHi, a great source code syntax highlighter.

In the style of BBCode, I want to use [ code=language ] [ /code ] tags. I’ve got a function that takes a string, checks it for a [ code tag, and then uses a preg_match_all to grab all the tags.
It then instantiates the GeSHi class, does the parsing, and then I used a str_replace to replace the old [ code ] tags with the highlighted code. See my function below:

[code]function highlight_code($string)
{
// First things first: If there aren’t any “[code]” strings in the message, we don’t
// need to process it at all.
if (!strpos(strtolower($string), “[code”))
{
return $string;
}

// Get the code tags
preg_match_all("#[code=(.*?)](.*?)[/code]#si", $string, $matches, PREG_SET_ORDER);

foreach($matches as $match)
{
	$ge = new GeSHi($match[2], $match[1]);
	$ge->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);
	$ge->set_header_content("<div style="color:#fff;background:rgb(33,33,33);"><LANGUAGE></div>");
	$ge->set_overall_style('background:rgb(22,22,22);', true);

	$replacement = "<div>" . $ge->parse_code() . "</div>";
	$string = str_replace($match[0], $replacement, $string);
}
return $string;

}[/code]

Pretty straight forward right?

Well here’s what I’m running into:
When I’m parsing blocks of PHP code that contain a regex, it’s somehow breaking the function.

On this blog, I posted this function as a code sample, and it indeed broke my formatting inside the preg_match_all().

It get’s down to here before breaking:

1. include_once(geshi.php); 2. function highlight_code($string) 3. { 4. // First things first: If there aren't any "[code]" strings in the message, we don't 5. // need to process it at all. 6. if (!strpos(strtolower($string), &quot;[code&quot;)) 7. { 8. return $string; 9. } 10. ? 11. // Get the code tags 12. preg_match_all(&quot;#[code=(.*?)](.*?)

Any ideas anyone? I’m thinking I might need an escape routine somewhere, or maybe even just to use a literal in there somewhere…

Any ideas are appreciated!

It is not possible to give you advise without seeing the code of the geshi.php file. Can you post it here, or is it too large?

Sponsor our Newsletter | Privacy Policy | Terms of Service