views:

258

answers:

1

Having trouble with pattern and replacement. How can I make the replacement echo a final product such as

INSERT INTO `table` (`person`, `file`) VALUES
('test','test'),
('test2','test2'),
('test3','test3');

I am trying to insert the string into SQL but I need to format the current string below to do so, and I need to have the last part of the string test3:test3 or whatever the text may be to close the SQL pattern ('test3','test3');

<?php
$string = 'test:test test2:test2 test3:test3';
$pattern = '';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>

Also, can it also have a string such as this? '[email protected]:test test2:test2' whereas the email will be before the colon at ALL times.

+1  A: 

Try something like this:

$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";

An explanation:

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 ', ('
Bart Kiers
THAT IS AMAZING. Works as to what I asked. How would I make it so that I can put emails in the string. 'test:test test2:test [email protected]:test3' ? But the emails will only be in the first part of the string before the colon...
Homework
Joey, see my edit.
Bart Kiers
@Bart Thanks so much. I'm so inexperienced with this, I have been fooling around with it for an hour now.
Homework
No problem. Just make sure you understand what you're doing (read my explanation carefully).
Bart Kiers