[英]remove specific html tags using php
Since I dont want to use stip_tags function of php instead of I want to replace <script> and </script>
to empty string so that output should be alert(1). 由于我不想使用php的stip_tags函数,而不是想将
<script> and </script>
替换为空字符串,因此输出应为alert(1)。
Input:-
<script>alert(1)</script>
输入:-
<script>alert(1)</script>
Output:- alert(1)
输出:-alert(1)
how to achieve it. 如何实现。
Either use a simple replace: 使用简单的替换:
$string = str_replace(array("<script>","</script>"), "");
or a RegEx: 或正则表达式:
$string = preg_replace("/<script.*?>(.*)?<\/script>/im","$1",$string);
echo strip_tags($text, '<p><strong><a>');
只需在第二个参数中说明您不想删除的内容即可
I guess you want to prevet XSS attacks, you shouldn't merely worry about script
tags, someone might exploit it like this: <a href="http://anywhere.com" onClick="alert(1);">test</a>
(this is a very basic way though). 我想您想阻止XSS攻击,您不应该只担心
script
标签,否则有人可能会这样利用它: <a href="http://anywhere.com" onClick="alert(1);">test</a>
(尽管这是一种非常基本的方式)。
If you only want the script
tag, with no attributes, to be filtered: 如果只希望过滤没有属性的
script
标签,请执行以下操作:
str_replace(array('<script>', '</script>'), array('', ''), $str);
You should improve this using Regex; 您应该使用Regex改进它; using preg_match'es and preg_replaces (or only preg_replaces) you can match and/or replace the script tag with its attributes.
使用preg_match's和preg_replaces(或仅使用preg_replaces),您可以使用其属性匹配和/或替换script标签。 Or even have more protection against XSS.
甚至对XSS都有更多保护。
Edit: or even a regex like /<script>(.+)<\\/script>/
then store what between the brackets into a variable then print it. 编辑:甚至是正则表达式,例如
/<script>(.+)<\\/script>/
然后将方括号之间的内容存储到变量中,然后打印出来。
Try this comrade.. 试试这个同志
$strn = "<script>alert(1)</script>";
$ptrn = "=^<script>(.*)</script>$=i";
echo preg_match( $ptrn, $strn, $mtchs ); // 0 means fail to matche and 1 means matches was found!
var_dump( $mtchs );
results in 结果是
1array(2) {
[0]=> string(25) ""
[1]=> string(8) "alert(1)"
}
Easy way is using StripTags . 简单的方法是使用StripTags 。
go to StripTags github and download or install via composer. 转到StripTags github并通过composer下载或安装。 this class has a method called
only
that do this for you! 此类有一个
only
您执行此操作的方法!
use Mimrahe\StripTags\Stripper;
$stripper = new Stripper();
$stripper->text('<a href="#">link</a><p>some paragraph</a>');
$stripper->only(['p']);
echo $stripper->strip(); // prints '<a href="#">link</a>some paragraph'
You can always use strip_tags()
with a second parameter containing the allowable tags. 您始终可以将
strip_tags()
与包含允许标签的第二个参数一起使用。
Alternativly, use... 或者,使用...
preg_replace('/<script>(.*)</script>/i', '$1', $input);
Note, not tested. 注意,未经测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.