strip_tags: Behavior of the "allowed_tags" Argument Changed

As of PHP 5.3.4, strip_tags() will ignore self-closing tags (<br/>) provided in the allowed_tags argument. Regular tags (<br>) in that argument will preserve both types of tags:

$allowedTags = '<br/>'; // This no longer has any effect.
strip_tags('Line1<br/>Line2<br></br>', $allowedTags);
$allowedTags = '<br>'; // This now preserves both types of <br> tags.
strip_tags('Line1<br/>Line2<br></br>', $allowedTags);

See execution result.

Solution

The first step is to modify the allowed_tags argument to make all tags not self-closing. This will preserve all the specified tags, regardless of whether they are self-closing or not:

$allowedTags = '<br>';

If you need your code to work across both PHP versions, then you may opt to use both tags. The old version will preserve both the specified tags. The new version will ignore the self-closing tag, while still preserving both as per the new behavior of the regular tag:

$allowedTags = '<br><br/>';

See execution result.

These solutions assume that your existing code does not need to distinguish self-closing tags when stripping them, as that distinction is no longer possible. If your code logic relied on that distinction, then you need to revisit your code to remove that reliance.

See Also