开发者

PHP: SQL output regex problem

开发者 https://www.devze.com 2023-01-31 10:04 出处:网络
Code <?php $sql = file_get_contents(\'source.sql\'); $regex = \'/CREATE TABLE IF NOT EXISTS|INSERT INTO|ALTER TABLE `[0-9a-zA-Z-_]+`/\';

Code

<?php
$sql = file_get_contents('source.sql');
$regex = '/CREATE TABLE IF NOT EXISTS|INSERT INTO|ALTER TABLE `[0-9a-zA-Z-_]+`/';
$matches = array();
preg_match_all($regex, $sql, $matches);
print_r($matches);
?>

SQL

CREATE TABLE IF NOT EXISTS `adminnotification_inbox` (
  `notification_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `severity` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `date_added` datetime NOT NULL,
  `title` varchar(255) NOT NULL,
  `description` text,
  `url` varchar(255) NOT NULL,
  `is_read` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `is_remove` tinyint(1) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`notification_id`),
  KEY `IDX_SEVERITY` (`severity`),
  KEY `IDX_IS_READ` (开发者_C百科`is_read`),
  KEY `IDX_IS_REMOVE` (`is_remove`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `admin_assert` (
  `assert_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `assert_type` varchar(20) NOT NULL DEFAULT '',
  `assert_data` text,
  PRIMARY KEY (`assert_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='ACL Asserts' AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `admin_role` (
  `role_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(10) unsigned NOT NULL DEFAULT '0',
  `tree_level` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `sort_order` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `role_type` char(1) NOT NULL DEFAULT '0',
  `user_id` int(11) unsigned NOT NULL DEFAULT '0',
  `role_name` varchar(50) NOT NULL DEFAULT '',
  PRIMARY KEY (`role_id`),
  KEY `parent_id` (`parent_id`,`sort_order`),
  KEY `tree_level` (`tree_level`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COMMENT='ACL Roles' AUTO_INCREMENT=4;

INSERT INTO `admin_role` (`role_id`, `parent_id`, `tree_level`, `sort_order`, `role_type`, `user_id`, `role_name`) VALUES
(1, 0, 1, 1, 'G', 0, 'Administrators'),
(3, 1, 2, 0, 'U', 1, 'Template');

I'm trying to understand why above the code doesn't show tables names in output,just insert and create statements ...

Output

Array ( [0] => Array ( [0] => CREATE TABLE IF NOT EXISTS [1] => CREATE TABLE IF NOT EXISTS [2] => CREATE TABLE IF NOT EXISTS [3] => INSERT INTO ) [1] => Array ( [0] => [1] => [2] => [3] => ) )


It's because the [0-9a-zA-Z-_]+ part is only in the third part of your "or" (and you don't have any ALTER TABLE statements). Use

'/(?:CREATE TABLE IF NOT EXISTS|INSERT INTO|ALTER TABLE) `[0-9a-zA-Z-_]+`/'


As Spiny said, the table name match is part of the third or section. To split it out you could use:

$regex = '/(CREATE TABLE IF NOT EXISTS|INSERT INTO|ALTER TABLE) (`[0-9a-zA-Z-_]+`)/';
0

精彩评论

暂无评论...
验证码 换一张
取 消