0

パターンと交換に問題があります。交換用エコーを次のような最終製品にするにはどうすればよいですか?

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'一方、電子メールは常にコロンの前にあります。

4

1 に答える 1

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 ', ('
于 2009-11-11T21:08:27.790 に答える