From b7ce9a84f0775eb24f0a27d3816bf57b774a2927 Mon Sep 17 00:00:00 2001 From: Michael Krelin Date: Sat, 02 Feb 2008 10:50:48 +0000 Subject: added util::attr_escape escaping string for inclusion into x(ht)ml attributes Signed-off-by: Michael Krelin --- diff --git a/include/opkele/util.h b/include/opkele/util.h index 6f3ddf6..719f951 100644 --- a/include/opkele/util.h +++ b/include/opkele/util.h @@ -100,6 +100,13 @@ namespace opkele { string url_encode(const string& str); /** + * Make string suitable for using as x(ht)ml attribute. + * @param str string to escape + * @return escaped string + */ + string attr_escape(const string& str); + + /** * Convert number to string * @param l number * @return string representation diff --git a/lib/util.cc b/lib/util.cc index 54d6535..b7bc437 100644 --- a/lib/util.cc +++ b/lib/util.cc @@ -161,6 +161,25 @@ namespace opkele { return rv; } + string attr_escape(const string& str) { + static const char *unsafechars = "<>&\n\"'"; + string rv; + string::size_type p=0; + while(true) { + string::size_type us = str.find_first_of(unsafechars,p); + if(us==string::npos) { + if(p!=str.length()) + rv.append(str,p,str.length()-p); + return rv; + } + rv.append(str,p,us-p); + rv += "&#"; + rv += long_to_string((long)str[us]); + rv += ';'; + p = us+1; + } + } + string long_to_string(long l) { char rv[32]; int r=snprintf(rv,sizeof(rv),"%ld",l); -- cgit v0.9.0.2