简体   繁体   中英

PHP htmlspecialchars() or htmlentities() with exception

How can I define an exception for htmlspecialchars() or htmlentities() ? I would like to have all special characters converted to be HTML safe except for <strong><b><i><em><br>

Easiest way would be to convert your string with htmlentities and then use preg_replace to replace back the selected tags:

<?php
$string = '<p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>';
$encoded_string = htmlentities($string);

$encoded_string = preg_replace('/&lt;(\/?(strong|b|i|em|br))&gt;/', '<$1>', $encoded_string);

echo($encoded_string); 
//outputs: &lt;p&gt;<strong>A <i>test</i> string with a &lt;a href=&quot;#&quot;&gt;Test link&lt;/a&gt;</strong>&lt;/p&gt;

Of course if you want to handle arguments inside the tags as well, then the regex pattern needs some work, although these tags are generally lacking any argument.

I have slightly modified the solution by @MrLumie by adding another (.?\/)? to retain both <br> and <br /> (albeit converting them both to <br> ):

/&lt;(\/?(strong|b|i|em|br))(.?\/)?&gt;/i

as shown here: https://regex101.com/r/G6D2lj/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM