Remove defined HTML tags including content from a string with PHP

Speaks many languages, but currently only uses PHP, JavaScript and WordPress (I consider it its own language, since it's a big sandbox).
Search for a command to run...

Speaks many languages, but currently only uses PHP, JavaScript and WordPress (I consider it its own language, since it's a big sandbox).
No comments yet. Be the first to comment.
When there are problems with one's WordPress website, it happens that one has to create a user without having access to the database or the WordPress admin. Then it is useful to be able to create or log in a user using FTP. So here you will learn how...

Occasionally it happens that overlaps occur in a large table and the message Duplicate entry '0' for key 'PRIMARY' for query then gets the upper hand in the error logs. This error can be fixed quite easily with a short line of SQL. Fix duplicate entr...

WordPress is packed with useful features. It is easy to lose the overview. Here you will find a selection of functions that deal with arrays and objects. A small collection of useful functions that you can always use, if you know that they exist. wp_...

As a rule, searches are created with the MySQL LIKE. This usually works very well, as long as the database table is not too large. However, if you work with a large database (millions+ entries), then you quickly notice how long a search in it actuall...

Recently, a friend asked me to send a script to remove pre tags from a string, including content. He uses a script to calculate the reading time for the content, but doesn't want the pre-tags to be included in the scoring. So if you ever have a similar problem, this post might help you.
In our example, we determine the tag and say that all pre-tags are affected. That is, our regular expression looks like this:
/<pre[^>]*>([\s\S]*?)<\/pre[^>]*>/m
If it should only affect h1 headings, it looks like this:
/<h1[^>]*>([\s\S]*?)<\/h1[^>]*>/m
And if all links are to be filtered out, it looks like this:
/<a[^>]*>([\s\S]*?)<\/a[^>]*>/m
You can use the regular expression for pretty much any tag.
Now we want to replace the tags including content with an empty string, that is, so that they are no longer present in the string. This could look like this:
$regex = '/<pre[^>]*>([\s\S]*?)<\/pre[^>]*>/m';
$string = 'My long text with <pre>some code</pre> and so on.'
$string = preg_replace($regex, '', $string);
Now all pre tags are replaced with an empty string. From this, you can also build a function that is quite flexible:
function pxbt_strip_tag(string $tag = 'pre', string $string) {
$regex = '/<' . $tag . '[^>]*>([\s\S]*?)<\/' . $tag . '[^>]*>/m';
return preg_replace($regex, '', $string);
}
You can use this function as often as you like. You can find examples here:
$string = 'My string';
// remove h1
$string = pxbt_strip_tag('h1', $string);
// remove p
$string = pxbt_strip_tag('p', $string);
// remove pre
$string = pxbt_strip_tag('pre', $string);