【问题标题】:Replace by pattern in PHP [duplicate]用PHP中的模式替换[重复]
【发布时间】:2016-01-27 15:20:33
【问题描述】:

我有一个字符串:

CREATE TABLE IF NOT EXISTS  `coupons` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(255) NOT NULL,
  `off` int(11) NOT NULL,
  `order` int(11) NOT NULL,
  `value` tinyint(1) DEFAULT NULL,
  `status` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

CREATE TABLE `currency` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(10) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `prefix` varchar(12) DEFAULT NULL,
  `suffix` varchar(12) DEFAULT NULL,
  `format` char(1) DEFAULT NULL,
  `decimals` char(1) DEFAULT NULL,
  `exchange` float(15,6) DEFAULT NULL,
  `round` int(5) NOT NULL,
  `published` tinyint(1) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

并且想将“CREATE TABLE”替换为“CREATE TABLE IF NOT EXISTS”。 我该怎么做?

谢谢!

【问题讨论】:

  • 因为它看起来像一次性操作,任何文本编辑器中的“查找和替换”工具都应该这样做:)
  • 认真的吗?有这么多 PHP replace strings questions already。通过一点点搜索,应该很明显该做什么。这个问题对社区没有附加价值。

标签: php mysql replace


【解决方案1】:

在 PHP 中(如果你真的需要以编程方式进行)你会做这样的事情(假设 $string 是你的变量包含两个 SQL 命令):

$string = preg_replace('/CREATE\sTABLE\s+`/i', 'CREATE TABLE IF NOT EXISTS `', $string);

作品:https://gist.github.com/jpaljasma/8355c57cc5608c4c4ff8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2017-03-07
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多