In Qt5, it's QString::toHtmlEscaped
, e.g.:
QString a = "Hello, <span class=\"name\">Bear</span>!";
// a will contain: Hello, <span class="name">Bear</span>!
QString b = a.toHtmlEscaped();
// b will contain: Hello, <span class="name">Bear</span>!
This is direct equivalent of the htmlspecialchars
in PHP. It replaces the Qt::escape
function (mentioned by Amartel), which does the same thing but is now obsolete.
The Qt::convertFromPlainText
function (also mentioned by Amartel) still exists in Qt 5, but it does more than PHP's htmlspecialchars
. Not only it replaces <
with <
, >
with >
, &
with &
, "
with "
but also does additional handling of whitespace characters (space, tab, line feed, etc) to make the generated HTML look visually similarly to the original plain text. Particularly, it may put <p>…</p>
/<br>
for linefeeds, non-breaking spaces for spaces and multiple non-breaking spaces for tabs. I.e. this function is not just htmlspecialchars
, it's even more comprehensive than nl2br(htmlspecialchars($s))
combination.
Note that unlike the PHP's htmlspecialchars
with ENT_QUOTES
, none of the Qt functions listed in this answer replace single quote ('
) with '
/'
. So, for example, QString html = "<img alt='" + s.toHtmlEscaped() + "'>";
won't be safe, only QString html = "<img alt=\"" + s.toHtmlEscaped() + "\">";
will. (However, as <
is replaced and '
has no special meaning outside <…>
, something like QString html = "<b>" + s.toHtmlEscaped() + "</b>";
would also be safe.)