[php] Replacing certain characters within a part of a string.

Results 1 to 2 of 2
  1. #1
    Fuck you, I'm a dragon Pieman is offline
    MemberRank
    Apr 2005 Join Date
    The NetherlandsLocation
    7,414Posts

    [php] Replacing certain characters within a part of a string.

    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:
    Code:
    &lt;?php echo &quot;test&quot;; ?&gt;
    Non-highlighted outputs:
    Code:
    <?php echo "test"; ?>
    Highlighted with highlight_string outputs:
    PHP Code:
    &lt;?php echo &quot;test&quot;; ?&gt
    Highlighted with my script:
    PHP Code:
    <?php echo "test"?>
    How does it work?
    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:
    PHP Code:
    <?php
    //Define a string
    $str "[tag]&lt;?php echo &quot;test&quot;; ?&gt;[/tag]";

    //Get the parts that need to be replaced.
    preg_match_all("/\[tag](.*?)\[\/tag]/is"$str$matchesPREG_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('/\&amp\;/','/\&lt\;/','/\&gt\;/','/\&quot\;/'), array('&''<''>''"'), $matches[$i][1]), true);
        
        
    //Put above line in the complete string.
        
    $str preg_replace("/\[tag](.*?)\[\/tag]/is"$code$str1);
        
        
    $i ++;

    }

    echo 
    $str;
    ?>
    Thought I'd share it, because I found it quite useful. ^^


  2. #2
    Gamma Daevius is offline
    MemberRank
    Jun 2007 Join Date
    NetherlandsLocation
    3,252Posts

    Re: [php] Replacing certain characters within a part of a string.

    Ah, you got it to work :), nice ;)



Advertisement