RegalCoding.com

A Programming Blog

Hello mobile user!

Adding some HTML tokens

I mentioned in my previous post that in order to control what is output to the screen, I escape some characters so that rather than display, for instance, a less than sign '<' it will actually output some character codes that are rendered to look like the same thing, but will not instruct your browser to treat it as an HTML tag.

This is all fine and well and helps prevent a malicious user from inserting javascript by doing something like <script></script> however there are instances where I would like to use some HTML tags in my posts. Namely, I'd like to be able to use the <pre> tag for displaying code snippets, and the <a href=''>link</a> tags for creating links.

In order to do that without allowing other HTML tags to be included, I created a token set which I can use to indicate where various HTML tags should be included by including the following lines to filter my content.

$content = preg_replace_callback('/[ code](.|n)*?[ /code]/','ConvertTag_Code',$content);
$content = preg_replace_callback('/[ url=.*?](.|n)*?[/url]/','ConvertTag_URL',$content);


As well as the corresponding functions which are called within those preg_replace_callback commands:
if (!function_exists(ConvertTag_Code)) {
	function ConvertTag_Code($arr){
		//we only need $arr[0]
		$text = str_ireplace('[ code]','<pre>',$arr[0]);
		$text = str_ireplace('[ /code]','</pre>',$text);
		$text = str_ireplace('&#13;&#10;',"n",$text);
		return $text;
	}
}

if (!function_exists(ConvertTag_URL)) {
	function ConvertTag_URL($arr){
		//we only need $arr[0]
		$text = str_ireplace('[/url]','</a>',$arr[0]);
		$text = str_ireplace("[url=","<a href='",$text);
		$text = str_ireplace("]","'>",$text);
		return $text;
	}
}


I can now specifically indicate within my text where I want certain HTML tags to appear, without allowing the presence of any other tags.

This code also allows me to safely place links on the site using the [ url] tags. For more information about the preg_replace_callback command, reference php.net

This is very similar to BBCode, which you may have seen in use on some web forums. I may add more functionality as the need arises; an img tag is a likely candidate, so that I may include some graphics with my posts.

For my next update, I believe I will edit the template and CSS files so that this blog is a little easier to read; after that, I will likely add some pages so that it doesn't all display on one long page.

Check back soon!

Category: Cms