How to toggle HTML entities

I found this interesting problem yesterday. I don’t see any practical use case, but still it is a nice one and it could be used in a test about problem solving skills. The following function is based on Karolis’ solution, which was the cleanest.

function toggle_html_entities($subject)
    return preg_replace('/(.*?)(<.*?>|$)/se', 
        'html_entity_decode("$1").htmlentities("$2")', $subject);

The interesting thing is that it’s a real toggle, meaning that

$subject == toggle_html_entities(toggle_html_entities($subject))


Leave a Reply

Your email address will not be published. Required fields are marked *