Skip to content

Instantly share code, notes, and snippets.

@condor-bird
Created April 22, 2018 11:23
Show Gist options
  • Save condor-bird/da22f3dbe3909406bfb96a0ebf185a65 to your computer and use it in GitHub Desktop.
Save condor-bird/da22f3dbe3909406bfb96a0ebf185a65 to your computer and use it in GitHub Desktop.
htmlspecialchars only on code tags
<?php
// htmlspecialchars only on <code></code> tags.
// test data
$textToScan = "Hi <code>test12</code><br>
Line 2 <code><br>
Test <b>Bold</b><br></code><br>
";
// the regex pattern (case insensitive & multiline
$search = "~<code>(.*?)</code>~is";
// first look for all CODE tags and their content
preg_match_all($search, $textToScan, $matches);
// now replace all the CODE tags and their content with a htmlspecialchars() content
foreach($matches[1] as $match){
$replace = htmlspecialchars($match);
// now replace the previously found CODE block
$textToScan = str_replace($match, $replace, $textToScan);
}
// output result
echo $textToScan;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment