All pastes #979281 Raw Edit

SQL highlight

public php v1 · immutable
·published 2008-04-10 06:42 UTC
rendered paste body
<?php/**  * Tokenizes text that looks something like SQL. */function tokenizeSQL( $SQL ){	$functions = array ( 'concat', 'if' );	$token = '\\(|\\)|[\']|"|\140|[*]|,|&lt;|>|&lt;>|=|[+]';	$terminal = $token.'|;| |\\n';	$result = array();	$string = $SQL;	$string = ltrim($string);	$string = rtrim($string,';').';'; // always ends with a terminal	$string = preg_replace( "/[\n\r]/s", ' ', $string );	while( 		   preg_match( "/^($token)($terminal)/s", $string, $matches ) ||		   preg_match( "/^({$token})./s", $string, $matches ) ||		   preg_match( "/^([a-zA-Z0-9_.]+?)($terminal)/s", $string, $matches) 		  )	{		$t = $matches[1];		if ($t=='\'')		{			// it's a string			$t = tokSingleQuoteString( $string );			array_push($result, $t);		}		else if ($t=="\140")		{			// it's a backtick string (a name)			$t = tokBackQuoteString( $string );			array_push($result, $t);		}		else if ($t=='"')		{			// it's a double quoted string (a name in normal sql)			$t = tokDoubleQuoteString( $string );			array_push($result, $t);		}		else		{			array_push($result, $t);		}		$string = substr( $string, strlen($t) );		$string = ltrim($string);	}	return $result;}function tokSingleQuoteString( $string ){	// matches a single-quoted string in $string	// $string starts with a single quote	preg_match('/^(\'.*?\').*$/s', $string, $matches );	return $matches[1];}function tokBackQuoteString( $string ){	// matches a back-quoted string in $string	// $string starts with a back quote	preg_match('/^([\140].*?[\140]).*$/s', $string, $matches );	return $matches[1];}function tokDoubleQuoteString( $string ){	// matches a Double-quoted string in $string	// $string starts with a double quote	preg_match('/^(".*?").*$/s', $string, $matches );	return $matches[1];}$mysql_functions = array('IN','concat');$mysql_keywords = array('SELECT','UPDATE','DELETE','INSERT','FROM','WHERE','ORDER BY','DESC','ASC','LIMIT');$mysql_bool = array('AND','OR','NOT');$sql ="SELECT * FROM datalink WHERE id=1 = concat(1,2,3,4) AND DeviceId='Some string with  strange chars );' ORDER BY scaleMax DESC LIMIT 2";$sql =tokenizeSQL($sql);	/*Function*/	$sql = preg_replace('#'.implode('|',$mysql_functions).'#','<span style="color: purple;">$0</span>',$sql);	//var_dump($sql);	$sql = preg_replace('#'.implode('|',$mysql_keywords).'#','<span style="color: blue;">$0</span>',$sql);	$sql = preg_replace('#'.implode('|',$mysql_bool).'#','<span style="color: black;">$0</span>',$sql);	$sql = preg_replace('#^(\\'."'".'|\\").*#','<span style="color: red;">$0</span>',$sql);	$sql = preg_replace('#[0-9]+\.?[0-9]*#','<span style="color: darkred;">$0</span>',$sql);echo implode(' ',$sql)?>