techno surprises

September 4, 2008

C# source code for strip_tags in PHP

Filed under: c, c sharp, csharp, php, strip_tags — Tags: , , , , , , , — Mustafa Turan @ 11:52 pm

Source to download: http://mustafaturan.net/download/lectures/csharp/strip_tags_csharp.txt

// as a namespace do not forget to add: using System.Text.RegularExpressions;
static string strip_tags(string str, string allowed_tags)
{
/*
// Coder: Mustafa Turan
// Date: 05.09.2008
// Contact:
// http://mustafaturan.net/
// https://mustafaturan.wordpress.com/
// wm [ #at# ] mustafaturan.net
// Licence: GNU and MIT Licence
// EXAMPLES
// —>     function call1: strip_tags(“<a href=\”asdadsadsad.html\”>doctor</a> <p>pirasa</p> <img src=\”asd.jpg\” /> <h1>hey you</h1>”, “<a>,<p>,<img />”)
// —>     result: <a href=””>doctor</a> <p>pirasa</p> <img src=”asd.jpg” /> hey you
// —>     function call2: strip_tags(“<a href=\”asdadsadsad.html\”>doctor</a> <p>pirasa</p> <img src=\”asd.jpg\” /> <h1>hey you</h1>”, “”)
// —>     result: doctor pirasa hey you
*/

// START
// pattern for getting all tags
string pattern_for_all_tags = “</?[^><]+>”;

// pattern for allowed tags
string allowed_patterns = “”;
if(allowed_tags!=””){
// get allowed tags if any exists
Regex r = new Regex(“[\\/<> ]+”);
allowed_tags = r.Replace(allowed_tags,””);
string[] allowed_tags_array = allowed_tags.Split(‘,’);
foreach (string s in allowed_tags_array)
{
if (s == “”) continue;
// Definin patterns
string p_1 = “<” + s + ” [^><]*>$”;
string p_2 = “<” + s + “>”;
string p_3 = “</” + s + “>”;
if(allowed_patterns!=””)
allowed_patterns += “|”;
allowed_patterns += p_1 + “|” + p_2 + “|” + p_3;
}
}

// Get all html tags included on string
Regex strip_tags = new Regex(pattern_for_all_tags);
MatchCollection all_tags_matched = strip_tags.Matches(str);

if (allowed_patterns != “”)
foreach (Match m in all_tags_matched)
{
Regex r_1 = new Regex(allowed_patterns);
Match m_1 = r_1.Match(m.Value);
if (!m_1.Success)
{
// if not allowed replace it
str = str.Replace(m.Value, “”);
}
}
else
// if not allow anyone replace all
str = strip_tags.Replace(str, “”);
return str;
}

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.