Only Convert HTML Entity's That are Not in "<" & ">"

Discussion in 'PHP' started by FishSword, Oct 3, 2010.

  1. #1
    Hiya! ;)

    I have a script that displays HTML. How do I convert HTML Entity's that are not inside the "<" and ">" symbols.

    In the following example, only the items shown in bold and blue should be coverted to their HTML equivalent codes. e.g. &pound;

    <div name="divname" style="width: 200px; height: 100px;">[COLOR=red]I[COLOR=blue][B]'[/B][/COLOR]ve got to save[B] [COLOR=blue]£[/COLOR][/B]3000 in order to buy a new car[B][COLOR=blue]![/COLOR][/B][/COLOR]</div>
    Code (markup):
    Many Thanks,
     
    FishSword, Oct 3, 2010 IP
  2. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #2
    Here is an example how to do it, but it doesn't convert the symbol ! because it hasn't entity:

    
    $text = "<div name=\"divname\" style=\"width: 200px; height: 100px;\">I've got to save £3000 in order to buy a new car!</div>";
    $chars = get_html_translation_table(HTML_ENTITIES,ENT_QUOTES);
    unset($chars["<"]);
    unset($chars[">"]);
    
    foreach(array_keys($chars) as $key){
        $text = preg_replace('/'.$key.'(?![^<]*[>])/i', $chars[$key], $text);
    }
    
    echo($text);
    
    PHP:
     
    s_ruben, Oct 4, 2010 IP
  3. FishSword

    FishSword Active Member

    Messages:
    131
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #3
    Excellent thanks. Out of interest, is it possible to do this without using a regular expression?
     
    FishSword, Oct 16, 2010 IP
  4. MakZF

    MakZF Well-Known Member

    Messages:
    390
    Likes Received:
    9
    Best Answers:
    1
    Trophy Points:
    140
  5. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #5
    $trans = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
    
    unset($trans['<'], $trans['>']);
    
    $str = <<<eof
    <div name="divname" style="width: 200px; height: 100px;">I've got to save £3000 in order to buy a new car!</div>
    eof;
    
    echo strtr($str, $trans);
    PHP:
    or

    function convert2entities($str) {
    
    //temporarily replace with placeholders...
    $str = str_replace(array('<', '>'), array('{OPEN}', '{CLOSE}'), $str);
    
    $str = htmlentities($str, ENT_QUOTES);
    
    //remove the placeholders...
    return str_replace(array('{OPEN}', '{CLOSE}'), array('<', '>'), $str);
    
    }
    
    $str = <<<eof
    <div name="divname" style="width: 200px; height: 100px;">I've got to save £3000 in order to buy a new car!</div>
    eof;
    
    echo convert2entities($str);
    PHP:
    Both are untested.
     
    Last edited: Oct 16, 2010
    danx10, Oct 16, 2010 IP