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? 'test@test.com:test test2:test2'
whereas the email will be before the colon at ALL times.
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 ', ('
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.