jdorn/sql-formatter 是一个轻量级的 PHP 类用于花样化 SQL 语句。
它支撑自动举行缩进、增加换行,以至还支撑语法高亮。
在敕令行内运用
该扩大包包括一个 bin/sql-formatter 可执行文件,可直接用于敕令行花样化 SQL。
运用 Composer 全局装置后便可运用该敕令了:
composer global require jdorn/sql-formatter sql-formatter "SELECT SOME QUERY;" // 直接花样化 // 或 echo "SELECT SOME QUERY;" | sql-formatter // 运用管道,更适合较大批的 SQL 语句
作为扩大包运用
SqlFormatter 类包括一个名为 format 的静态要领,它可以吸收一个 SQL 语句字符串作为参数,并返回花样化后运用 pre 标签包裹的 HTML 代码。
比方:
<?php require_once('SqlFormatter.php'); $query = "SELECT count(*),`Column1`,`Testing`, `Testing Three` FROM `Table1` WHERE Column1 = 'testing' AND ( (`Column2` = `Column3` OR Column4 >= NOW()) ) GROUP BY Column1 ORDER BY Column3 DESC LIMIT 5,10"; echo SqlFormatter::format($query);
输出:
只花样化不高亮
假如不须要高亮,只须要增加缩进和换行,请将第二个参数设置为 false 即可。
适用于输出毛病日记或许别的非 HTML 数据时。
<?php echo SqlFormatter::format($query, false);
输出:
只高亮不花样化
有个零丁的要领名为 highlight 可以保证原有的花样不被修改,只增加语法高亮。
适用于 SQL 已被优越花样化,需让它越发易读时。
紧缩查询语句
compress 要领可删除一切的 SQL 解释,并紧缩不必要的空格。
适用于输出多条查询语句,并使其易于复制粘贴到敕令行时。
-- This is a comment SELECT /* This is another comment On more than one line */ Id #This is one final comment as temp, DateCreated as Created FROM MyTable; echo SqlFormatter::compress($query);
输出:
SELECT Id as temp, DateCreated as Created FROM MyTable;
删除解释
假如你须要保存原有花样,但仍需删除 SQL 解释,你可以运用 removeComments 要领来替代 compress。
-- This is a comment SELECT /* This is another comment On more than one line */ Id #This is one final comment as temp, DateCreated as Created FROM MyTable; echo SqlFormatter::removeComments($query);
输出:
SELECT Id as temp, DateCreated as Created FROM MyTable;
将多条 SQL 语句分割为数组
另有一个与花样化无关的特征,可以将多条 SQL 语句星散为数组。
比方:
DROP TABLE IF EXISTS MyTable; CREATE TABLE MyTable ( id int ); INSERT INTO MyTable (id) VALUES (1),(2),(3),(4); SELECT * FROM MyTable; $queries = SqlFormatter::splitQuery($sql);
效果:
DROP TABLE IF EXISTS MyTable; CREATE TABLE MyTable ( id int ); INSERT INTO MyTable (id) VALUES (1),(2),(3),(4); SELECT * FROM MyTable;
为什么不运用正则表达式?
去看看 README 吧~https://github.com/jdorn/sql-formatter#why...。
以上就是在 PHP 中花样化并高亮 SQL 语句的细致内容,更多请关注ki4网别的相干文章!