I wrote this script because on my blog dangerous characters(", &, <, >) get replaced with their html(?) equilavent before inserting an entry/comment in to the database. Normally this isn't a problem but the highlight_string function in php doesn't display the characters normally.
Example:
Non-highlighted outputs:Code:<?php echo "test"; ?>
Highlighted with highlight_string outputs:Code:<?php echo "test"; ?>
Highlighted with my script:PHP Code:<?php echo "test"; ?>
How does it work?PHP Code:<?php echo "test"; ?>
The to-be replaced part of the string must be put between [tag][/tag] tags (or any other tag you prefer) The rest of the script is explained in the comments.
Bugs:
If tags are incorrectly nested or left un-closed the script doesn't work properly.
The script:
Thought I'd share it, because I found it quite useful. ^^PHP Code:<?php
//Define a string
$str = "[tag]<?php echo "test"; ?>[/tag]";
//Get the parts that need to be replaced.
preg_match_all("/\[tag](.*?)\[\/tag]/is", $str, $matches, PREG_SET_ORDER);
$i = 0;
//Use a while loop to replace all the parts that need to be replaced one by one.
while($i < count($matches)) {
//Replace the html-chars with their equilavent counter-parts.
$code = highlight_string(preg_replace(array('/\&\;/','/\<\;/','/\>\;/','/\"\;/'), array('&', '<', '>', '"'), $matches[$i][1]), true);
//Put above line in the complete string.
$str = preg_replace("/\[tag](.*?)\[\/tag]/is", $code, $str, 1);
$i ++;
}
echo $str;
?>



Reply With Quote![[php] Replacing certain characters within a part of a string.](http://ragezone.com/hyper728.png)

