Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove specific html tags using php

Tags:

html

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.

like image 542
Abhimanyu Avatar asked Oct 28 '25 15:10

Abhimanyu


2 Answers

Either use a simple replace:

$string = str_replace(array("<script>","</script>"), "");

or a RegEx:

$string = preg_replace("/<script.*?>(.*)?<\/script>/im","$1",$string); 
like image 148
klaustopher Avatar answered Oct 30 '25 07:10

klaustopher


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'