preg_replace没有给出好的结果

时间:2014-01-27 16:13:28

标签: php preg-replace

我有一个SQL文件,其中包含带有CONSTRAINT一词的行。 我想删除所有以'CONSTRAINT'开头的行和前一行的逗号(,),例如:

KEY `fk_node_node_type1_idx` (`tid`),
CONSTRAINT `fk_pages_users1` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_node_language1` FOREIGN KEY (`language`) REFERENCES `language` (`language`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_node_node_type1` FOREIGN KEY (`tid`) REFERENCES `node_type` (`tid`) ON DELETE NO ACTION ON UPDATE NO ACTION

... ...

KEY `fk_node_type_data_idx` (`tid`),
CONSTRAINT `fk_node_type_data` FOREIGN KEY (`tid`) REFERENCES `node_type` (`tid`) ON DELETE NO ACTION ON UPDATE NO ACTION

... ...

KEY `fk_node_has_image_node1_idx` (`nid`),
CONSTRAINT `fk_node_has_image_node1` FOREIGN KEY (`nid`) REFERENCES `node` (`nid`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_node_has_image_image1` FOREIGN KEY (`fid`) REFERENCES `file` (`fid`) ON DELETE NO ACTION ON UPDATE NO ACTION  

这是我的代码:

  

preg_replace(“/,\ s(。)CONSTRAINT(。)/”,“”,$ string);

它在单行上运行良好,但是当你有两到三行时,它就不能正常工作。

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

echo preg_replace("/,\v+CONSTRAINT .*?(?=,\v|$)/i","",$string);

答案 1 :(得分:1)

试试这个正则表达式:

preg_replace("/,\s?CONSTRAINT[^,]*/s" , "" , $string);

Regexpal demo

答案 2 :(得分:0)

您可以使用:

$result = preg_replace('~,\RCONSTRAINT .*(?<!,)~', '', $string);