简体   繁体   中英

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).

Input:- <script>alert(1)</script>

Output:- 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).

If you only want the script tag, with no attributes, to be filtered:

str_replace(array('<script>', '</script>'), array('', ''), $str);

You should improve this using Regex; using preg_match'es and preg_replaces (or only preg_replaces) you can match and/or replace the script tag with its attributes. Or even have more protection against XSS.

Edit: or even a regex like /<script>(.+)<\\/script>/ then store what between the brackets into a variable then print it.

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 .

go to StripTags github and download or install via composer. this class has a method called only that do this for you!

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.

Alternativly, use...

preg_replace('/<script>(.*)</script>/i', '$1', $input);

Note, not tested.

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