How to remove Script tags from WordPress Content
Remove Script tags from WordPress Content is required when you’re writing an API using WordPress posts and other data. Otherwise script tags and its contents inside will be prompt to public as post content. Here we are going to see how we can simply remove this script tags and its contents via preg_replace . preg_replace perform a regular expression search and replace. You can read more about this on php.net.
mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit = –1 [, int &$count]] );
Here we’ll go through one by one and get to know what are these. If you don’t want to get to know about these and if you just need the code please jump over and get your code.
The formation to search for. It can be either a string or an array with strings.
The string or array of strings to replace. What will happen if this parameter is a string and pattern parameter is an array. It will replaced all patterns by the string.
What to search and replace.
The maximum possible replacements can take. By default this is set to minus one (-1) that means there is no limit. If you need to limit, you can change this.
If count is specified, you can see the number of replacements done.
Remove Script Tags from WordPress Content
Lets see the code first.
$post_content = $post->post_content; $post_content = preg_replace('#<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript(.*%3F)%3E(.*%3F)%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />#is', ", $post_content);
$post_content variable has defined first and all post contents has been assigned to the $post_content variable. You can use your own variables. You can use same $post_content variable for filter the content. Once the post content gone through this preg_replace function all script tags and its contents within the script tags are removed. Now you’re done and you can use filtered content.
Hope you got something by reading this. Thanks for reading.