Current Location: Home> Latest Articles> How to Filter and Handle Custom Tags Using strip_tags and preg_replace Together

How to Filter and Handle Custom Tags Using strip_tags and preg_replace Together

gitbox 2025-08-26
<span class="hljs-meta"><?php
<hr>
<h2>How to Filter and Handle Custom Tags Using strip_tags and preg_replace Together</h2>
<p>In PHP, when dealing with HTML strings, it is often necessary to filter or replace certain tags. <code>strip_tags()

Here, the regular expression replaces all

tags with attributes with

tags having a new class.

3. Combining strip_tags and preg_replace for Custom Tag Filtering and Handling

The strip_tags function is simple and cannot check tag attributes or perform complex operations on the content inside tags. By combining it with preg_replace, you can first use regular expressions to convert custom tags into standard tags or adjust attributes, and then use strip_tags to filter out disallowed tags.

Example: We want to preserve only the and tags but convert a custom tag into , and for tags, keep only the href attribute.


$html = "This is <mytag>a custom tag</mytag>, plus <a href='http://example.com' title='title'>link</a>, and <b>bold</b>.";

// Step 1: Replace <mytag> with <span>
$html = preg_replace([
    '/<\/?mytag>/i'
], [
    function($matches) {
        return str_ireplace(['mytag','/mytag'], ['span','/span'], $matches[0]);
    }
], $html);

// Step 2: Filter out all <a> attributes except href
$html = preg_replace_callback(
    '/<a\s+([^>]*)>/i', function($matches) {
        // Keep only href attribute
        if (preg_match('/href\s*=\s*["\']?([^"\'>\s]+)["\']?/i', $matches[1], $hrefMatch)) {
            return '<a href="' . $hrefMatch[1] . '">';
        }
        return '<a>';
    }, $html
);

// Step 3: Use strip_tags to preserve only allowed tags
$result = strip_tags($html, '<b><a><span>');

echo $result;

In this way, the original is replaced with , the tag keeps only the href attribute, and overall only , , and tags are preserved while all other tags are removed.

4. Conclusion

Designing appropriate regular expressions and filtering logic according to your needs is key to implementing custom tag filtering and handling.

gitbox.net
Covering practical tips and function usage in major programming languages to help you master core skills and tackle development challenges with ease.
Repository for Learning Code - gitbox.net