Search code examples
htmlescapingsyntax-highlightingpre

How to fix the 'pre' tag's issues with left angle brackets '<'?


I hear this is a long-standing issue with the 'pre' tags — when you are displaying a code block inside <pre> tags, you need to escape all instances of < (left angle brackets).

Is there an automatic fix for this? — (I mean) so that I don't have to manually replace all instances of < with &lt; in every post I make.


Solution

  • My Suggestion as an "Auto" fix of sorts, is a str_replace on the string your putting into your pre tag. Assuming of course your using PHP, but each language has its equivalent I suppose.

    <pre>
    <?php
      $str = $variable_of_stuff_going_into_pre;
      $str = str_replace('<', '&lt;', $str);
      $str = str_replace('>', '&gt;', $str);
      echo $str;
     ?>
     </pre>
    

    That's kind of a simplified version of it. You can use arrays are your search/replace string as well.