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('/<(\/?(strong|b|i|em|br))>/', '<$1>', $encoded_string);
echo($encoded_string);
//outputs: <p><strong>A <i>test</i> string with a <a href="#">Test link</a></strong></p>
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>
):
/<(\/?(strong|b|i|em|br))(.?\/)?>/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.