Preparing HTML And PHP Code For Pubilishing On Websites

1st April 2009

I talked a while ago about Adding Code To Wordpress Blogs And Comments, but I decided that it needed a bit of code to do this automatically.

So here it is, prepared by the text processor.

  1. if ( isset($_POST["text"]) ) {
  2. $text = $_POST["text"];
  3. $text = stripslashes( $text );
  4. $input = array ( "/&/", "/'/", "/"/", "/</", "/
/", "/t/", "/(?", "&", "
" ); $temp = preg_replace($input, $output, $text); echo '
'; } ?>

There seems to be rather a lot going on here, but the process is quite simple. The preg_replace() function can take an array as an argument for the input and output parameters. When you do this the arrays will be matched up so that the second item in the input array will be replaced by the second item in the output array.

So here is a list of the things I am matching for and what they are replaced with.

  • /&/ This matches for any ampersand, we replace this with the encoded variant of &.
  • /'/ Find single quotes and encode them with '.
  • /\"/ Find double quotes and encode them with ".
  • / This matches all
  • />/ Same as above but the other way around, in this case the equivalent is >.
  • /\t/ Next we start matching for white space, the first is to find all tab characters and replace them with four   characters, like this     
  • /(?
  • /^\s$/m This matches for any line with nothing on it. These must be replaced with a single   character, but in order to keep the code as it was posted we add a
    tag, the final output would be  
  • /&/ Now that we have all of our tags encoded we need to re encode all of the & characters so that when the script prints out the content to a HTML page with all & translated to &.
  • /\r\n/ Finally, we find all of the new line characters and convert them to
    tags. You might want to change this to just \n if you are using a Linux format.

Before we do any of this we pass the text through the stripslashes() function. This is because sending the text over POST might add slashes to the " and ' characters. This call just removes them.

You can try out the processor if you want by going to the text process tool page.

Add new comment

The content of this field is kept private and will not be shown publicly.