PYTHON htmlspecialchars_decode

is this article helpful?
|
Python replacement for PHP's htmlspecialchars_decode [ edit | history ]
import re
try:
    from htmlentitydefs import entitydefs
except ImportError:  # Python 3
    from html.entities import entitydefs


def htmlspecialchars_decode_func(m, defs=entitydefs):
    try:
        return defs[m.group(1)]
    except KeyError:
        return m.group(0)  # use as is


def htmlspecialchars_decode(string):
    pattern = re.compile("&(\w+?);")
    return pattern.sub(htmlspecialchars_decode_func, string)

PHP htmlspecialchars_decode

PHP original manual for htmlspecialchars_decode [ show | php.net ]

htmlspecialchars_decode

(PHP 5 >= 5.1.0)

htmlspecialchars_decode Convert special HTML entities back to characters

Description

string htmlspecialchars_decode ( string $string [, int $quote_style= ENT_COMPAT ] )

This function is the opposite of htmlspecialchars(). It converts special HTML entities back to characters.

The converted entities are: &, " (when ENT_NOQUOTES is not set), ' (when ENT_QUOTES is set), < and >.

Parameters

string

The string to decode

quote_style

The quote style. One of the following constants:

quote_style constants
Constant Name Description
ENT_COMPAT Will convert double-quotes and leave single-quotes alone (default)
ENT_QUOTES Will convert both double and single quotes
ENT_NOQUOTES Will leave both double and single quotes unconverted

Return Values

Returns the decoded string.

Examples

Example #1 A htmlspecialchars_decode() example

<?php
$str 
'<p>this -&gt; &quot;</p>';

echo 
htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($strENT_NOQUOTES);
?>

The above example will output:

<p>this -> "</p>
<p>this -> &quot;</p>

See Also