Jump to content

[SOLVED] convert part of a string using preg_replace


nuttycoder

Recommended Posts

Hi Guys,

 

I'm trying to print some code snippets to the screen that's mixed with normal html what I'm trying to do is use htmlentities to convert the snippets. This would only convert text inside [ code ] [ /code ] tags.

 

Using preg_replace I've managed to isolate the snippets but I cannot use htmlentities without causing an error.

 

As I need to add the snippets back into the string it came from before bring printed.

 

Here's what I've been using replacing all code tags with <pre class="codeprint">snippets here</pre>

 

$pr->postDesc = preg_replace("/\[code\](.+?)\[\/code\]/is","<pre class=\"codeprint\">$1</pre>", $pr->postDesc);

 

An example of what $pr->postDesc contains:

 

<p>testing</p>

 

[ code ]

<?php echo $test;?>

[ /code ]

 

Hope you can understand what I mean.

Link to comment
Share on other sites

Alex kinda beat me to it, though his code has an error (using double quotes for the second parameter in create_function()).

 

You're best off using preg_replace_callback(), since using preg_replace() with the e modifier (as I guess you may have tried) gives us some escaping issues (article). Code:

 

<?php
$pr->postDesc = preg_replace_callback(
'~\[code\](.*?)\[/code\]~is',
create_function(
	'$matches',
	'return \'<pre class="codeprint">\' . htmlentities($matches[1], ENT_QUOTES) . \'</pre>\';'
),
$pr->postDesc
);
?>

 

I'm assuming you're using square brackets for your code tags, since that's what you did in the pattern you said you've been using.

 

If you want to syntax highlight the snippets, use highlight_string() instead of htmlentities().

Link to comment
Share on other sites

Thanks Guys I should have consulted the manual to see if there way a better way preg_replace_callback is the obvious choice now it's been pointed out to me :)

 

Works a treat.

 

I'm not using highlight_string as my code snippets are not limited to just php so I'm using google's prettify syntax highlight plugin.

 

Thanks again guys much appreciated!!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.