<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
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
$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
Designing appropriate regular expressions and filtering logic according to your needs is key to implementing custom tag filtering and handling.