Php 使用preg_replace格式化
在图案和替换方面有问题。如何使替换echo成为最终产品,例如Php 使用preg_replace格式化,php,sql,string,preg-replace,Php,Sql,String,Preg Replace,在图案和替换方面有问题。如何使替换echo成为最终产品,例如 INSERT INTO `table` (`person`, `file`) VALUES ('test','test'), ('test2','test2'), ('test3','test3'); 我正在尝试将字符串插入SQL,但我需要格式化下面的当前字符串才能这样做,并且我需要使用字符串的最后一部分test3:test3或任何文本来关闭SQL模式('test3','test3') <?php $string = 'tes
INSERT INTO `table` (`person`, `file`) VALUES
('test','test'),
('test2','test2'),
('test3','test3');
我正在尝试将字符串插入SQL,但我需要格式化下面的当前字符串才能这样做,并且我需要使用字符串的最后一部分test3:test3或任何文本来关闭SQL模式('test3','test3')强>
<?php
$string = 'test:test test2:test2 test3:test3';
$pattern = '';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
还有,它也可以有这样的字符串吗<代码>'test@test.com:test test2:test2',而电子邮件将始终位于冒号之前。请尝试以下操作:
$string = 'test:test test2:test2 test3:test3';
$patterns = array("/([^\s:]+):([^\s:]+)/", "/\s++\(/");
$replacements = array("('$1', '$2')", ", (");
$sql = 'INSERT INTO `table` (`person`, `file`) VALUES ' . preg_replace($patterns, $replacements, $string) . ';';
echo $sql . "\n";
解释:
Regex 1
([^\s:]+) # match one or more chars other than white space chars and colons and store it in group 1
: # match a colon
([^\s:]+) # match one or more chars other than white space chars and colons and store it in group 2
Replacement 1
( # insert a '('
'$1' # insert what is matched in group 1 and surround it with single quotes
, # insert ', '
'$2' # insert what is matched in group 2 and surround it with single quotes
) # insert a ')'
Regex 2
\s++ # match one or more white space chars
\( # match a '('
Replacement 2
, ( # insert ', ('
这几乎可以肯定是正则表达式的不当使用。当一个值包含冒号、单引号、换行符或任何其他在sql中具有特殊意义的字符数时,您会怎么做?不会有其他数据。我确信这一点。严格说来,测试是有偏见的:test@Bart非常感谢。我对这件事太没经验了,我已经胡闹了一个小时了。没问题。只要确保你明白你在做什么(仔细阅读我的解释)。