您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在 PHP 中格式化并高亮 SQL 语句

2025/4/3 6:01:09发布39次查看
jdorn/sql-formatter 是一个轻量级的 php 类用于格式化 sql 语句。
它支持自动进行缩进、添加换行,甚至还支持语法高亮。
在命令行内使用
该扩展包包含一个 bin/sql-formatter 可执行文件,可直接用于命令行格式化 sql。
使用 composer 全局安装后便可使用该命令了:
composer global require jdorn/sql-formattersql-formatter "select some query;" // 直接格式化// 或echo "select some query;" | sql-formatter // 使用管道,更适合较大量的 sql 语句
作为扩展包使用
sqlformatter 类包含一个名为 format 的静态方法,它可以接收一个 sql 语句字符串作为参数,并返回格式化后使用 pre 标签包裹的 html 代码。
例如:
<?phprequire_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 数据时。
<?phpecho 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 语句的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product