note 119442 deleted from function.preg-replace by cmb
| From: | cmb@php.net | Date: | Sun, 22 Sep 2019 07:58:37 +0000 |
| Subject: | note 119442 deleted from function.preg-replace by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212298@lists.php.net to get a copy of this message | ||
Note Submitter: hortonmj at hotmail dot com
----
If you want to avoid removing specific tags without allowing dangerous attributes you can replace
them with a custom format before using strip_tags().
For example if you want to keep <p>:
<?php
$text = "<p>hello
world</p><script>alert('hacked')</script>";
$text = str_replace("<p>", "[[[temp-tag=p]]]", $text);
$text = str_replace("</p>", "[[[temp-tag=/p]]]", $text);
$text = strip_tags($text);
$text = str_replace("[[[temp-tag=p]]]", "<p>", $text);
$text = str_replace("[[[temp-tag=/p]]]", "</p>", $text);
echo $text; // displays <p>hello world</p>alert('hacked')
?>
If you wish to allow specific tags attributes use regex_replace() like so:
<?php
$text = regex_replace("/<(p class=".*?")>", "[[[temp-tag=$1]]]",
$text);
?>
Be carefull doing this with href though. Make sure the atribute doesnt call javascript.
<?php
$text = preg_replace('/href="\s*javascript:.*?"/i', "", $text);
$text = regex_replace('/<(a href=".*?")>', [[[temp-tag=$1]]], $text);
?>