使用preg_replace格式化

时间:2009-11-11 20:56:29

标签: php sql string preg-replace

模式和替换有问题。如何使替换回声成为最终产品,例如

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',而电子邮件将始终在冒号之前。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$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 ', ('