note 119442 added to function.preg-replace
| From: | hortonmj at hotmail dot com | Date: | Mon, 06 Jun 2016 18:22:13 +0000 |
| Subject: | note 119442 added to function.preg-replace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205673@lists.php.net to get a copy of this message | ||
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);
?>
----
Server IP: 72.52.91.14
Probable Submitter: 64.49.83.98
----
Manual Page -- http://php.net/manual/en/function.preg-replace.php
Edit -- https://master.php.net/note/edit/119442
Del: integrated -- https://master.php.net/note/delete/119442/integrated
Del: useless -- https://master.php.net/note/delete/119442/useless
Del: bad code -- https://master.php.net/note/delete/119442/bad+code
Del: spam -- https://master.php.net/note/delete/119442/spam
Del: non-english -- https://master.php.net/note/delete/119442/non-english
Del: in docs -- https://master.php.net/note/delete/119442/in+docs
Del: other reasons-- https://master.php.net/note/delete/119442
Reject -- https://master.php.net/note/reject/119442
Search -- https://master.php.net/manage/user-notes.php