public function tesGetBetween() { $query = 'SELECT * FROM test'; $expected = "*"; $actual = String::getBetween($query, 'SELECT', 'FROM'); $this->assertEquals($expected, $actual); }
/** * get column to select */ public function getColumns() { // before this we have to disable functions $sql = $this->functions(false); $columns = trim(String::getBetween($sql, 'SELECT', 'FROM')); if ($columns && $columns != '' && strlen($columns) > 0) { $fields = explode(',', $columns); $data = array(); // explore multiple columns foreach ($fields as $column) { $column = trim($column); if (strpos($column, 'AS')) { $result = explode('AS', $column); $data[] = array('column' => trim(trim($result[0]), '`'), 'alias' => trim(trim($result[1]), '`')); } elseif (count($column_saperate = explode(' ', $column)) > 1) { $reverse_column = array_reverse($column_saperate); $data[] = array('column' => trim(trim($column_saperate[0]), '`'), 'alias' => $reverse_column[0]); } else { $data[] = array('column' => trim($column, '`'), 'alias' => ''); } } return $data; } else { return array(); } }
/** * get joins tables and condition of them */ public function joins() { $string = 'JOIN'; $positions = String::findPositions($this->sql, $string); if (count($positions)) { // check on join or more if (count($positions) == 1) { // we have usually USING or ON in joins mysql so we get tables and alias of theme $table = String::getBetween($this->sql, 'JOIN', 'ON'); if (!$table) { $table = String::getBetween($this->sql, 'JOIN', 'USING'); } if (!$table) { return array(); } $aliases = $this->getAliases($table); return array(array('table' => trim(trim($aliases[0]), '`'), 'alias' => isset($aliases[1]) ? trim(trim($aliases[1]), '`') : '')); } else { $tables = array(); $index = 0; foreach ($positions as $key => $position) { $index++; $next_position = String::findPositions($this->sql, 'ON', $position, false); if (!count($next_position)) { $next_position = String::findPositions($this->sql, 'USING', $position, false); } if (!count($next_position)) { continue; } else { $next_position = $next_position[0]; if (isset($positions[$index]) && $next_position > $positions[$index]) { continue; } $length = $next_position - $position; $table = substr($this->sql, $position + strlen('JOIN'), $length - strlen('JOIN')); $aliases = $this->getAliases($table); $tables[] = array('table' => trim(trim($aliases[0]), '`'), 'alias' => isset($aliases[1]) ? trim(trim($aliases[1]), '`') : ''); } } return $tables; } } else { return array(); } }
<?php require_once dirname(__FILE__) . '/vendor/autoload.php'; $parser = new PHPParser\Parser('SELECT * FROM ps_user'); use PHPParser\Tools\String; echo String::getBetween('SELECT', 's', 'l');