Notes & Code Snippets

Read notes about design & development, or useful scripts and bits of code from me

Parse an HTML page for Python code

April 01, 2011

Keywords: python php html

This script is intended to simulate the way PHP works when embedded in an HTML page. It will take an HTML page and find code blocks of Python, and execute them.

#! /usr/local/bin/python
def preprocess(__preprocess__file__):
    try:
        __preprocess__f__ = open(__preprocess__file__, 'r')
        __preprocess__execScript__ = ""
        __preprocess__execMode__ = False
        while True:
            __preprocess__x__ = __preprocess__f__.readline()
            if not __preprocess__x__:
                break
            if __preprocess__x__ == '<?\n':
                __preprocess__execMode__ = True
                __preprocess__x__ = ""
            if __preprocess__execMode__:
                if __preprocess__x__ == '?>\n':
                    exec(__preprocess__execScript__)
                    __preprocess__execScript__ = ""
                    __preprocess__execMode__ = False
                    __preprocess__x__ = ""
                else:
                    __preprocess__execScript__ += __preprocess__x__
            else:
                __preprocess__x__ = __preprocess__x__.replace('\n', '')
                if __preprocess__x__.find('<?=') is not -1:
                    __preprocess__y__ = ""
                    __preprocess__x__ = __preprocess__x__.split('<?=')
                    for __preprocess__z__ in __preprocess__x__:
                        __preprocess__found__ = __preprocess__z__.find('?>')
                        if __preprocess__found__ is not -1:
                            __preprocess__operation__ = __preprocess__z__[0:__preprocess__found__]
                            __preprocess__y__ += str(eval(__preprocess__operation__))
                            __preprocess__y__ += __preprocess__z__[__preprocess__found__ + 2:]
                        else:
                            __preprocess__y__ += __preprocess__z__
                    __preprocess__x__ = __preprocess__y__
                    del __preprocess__y__
                    del __preprocess__z__
                print __preprocess__x__
        __preprocess__f__.close()
    except Exception, e:
        print e

Back to top

Feedback generation

March 29, 2011

Keywords: php feedback

I use this class in everything I do. It's essential for validating user input, confirming actions, etc.
 
///////////////////////////////////////////////////////
//////  THIS CODE DEVELOPED BY BENJAMIN PITTMAN ///////
//////              www.bpittman.com            ///////
///////////////////////////////////////////////////////
 
class Feedback{
    private $type = 1;
    public $items = array();
    private $style = 1;
    private $label;
    
    function add($str){
        array_push($this->items, $str);
    }
    
    function type($str){
        if( $str == 'success' || $str == 1 )
            $this->type = 1;
        else if ($str == 'failure' || $str == 'fail' || $str == 'error' || $str == 'err' || $str == 2)
            $this->type = 2;
    }
    
    function style($str){
        if( $str == 'list' || $str == 1 )
            $this->style = 1;
        else if( $str == 'block' || $str == 2 )
            $this->style = 2;
    }
    
    function label($str){
        $this->label = $str;
    }
    
    function isEmpty(){
        if( count($this->items) > 0 )
            return false;
        else
            return true;
    }
    
    function execute(){
        $html = "";
        if( !$this->label )
            return false;
        $html .= "<div class='feedback'>\n";
        if( $this->type == 1 )
            $html .= "<div class='success'>\n";
        else if( $this->type == 2 )
            $html .= "<div class='failure'>\n";
        $html .= "<h1>" . $this->label . "</h1>\n";
        if( count($this->items) > 0 ){
            if( $this->style == 1 ){
                $html .= "<ul>\n";
                foreach( $this->items as $k=>$v ){
                    $html .= "<li>" . $v . "</li>\n";
                }
                $html .= "</ul>\n";
            }
            else if( $this->style == 2 ){
                foreach( $this->items as $k=>$v ){
                    $html .= "<p>" . $v . "</p>\n";
                }
            }
        }
        $html .= "</div>\n";
        $html .= "</div>\n";
        return $html;
    }
    
}

Back to top

Return content between delimiters

November 23, 2009

Keywords: php delimiter string

This is an incredibly useful PHP string function for retrieving content between delimiters, such as [bold][/bold]. Useful for parsing BBCode, or for parsing anything in general.
function extract_unit($string, $start, $end){
	$pos = strpos($string, $start);
	$pos2 = strpos($string, $end);
	if( ($pos || $pos == 0) && $pos2 && $pos2 > $pos ){
		$unit = (substr($string, $pos+strlen($start), $pos2-$pos-strlen($start)));
	}
	if( $unit )
		return $unit;
	else
		return false;
}

Back to top

Replace content in a string within delimiters

November 23, 2009

Keywords: str string replace delimit delimiters php

This script replaces content inside delimiters with whatever you want. It's like using str_replace when you only know the beginning and end of the string to be replaced.
function replace_content_inside_delimiters($start, $end, $new, $source) {
	return preg_replace('#('.preg_quote($start).')(.*)('.preg_quote($end).')#si', $new, $source);
}

Back to top

Javascript print_r equivalent

December 29, 2008

Keywords: javascript java script print_r printr php equivalent

Useful Javascript function that mimics PHP's print_r function.
function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>[" p "] => " typeof(theObj) "</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>[" p "] => " theObj[p] "</li>");
      }
    }
    document.write("</ul>")
  }
}

Back to top

1 2