2009-11-11 68 views
0

模式和替換有問題。我怎樣才能讓更換呼應的最終產品如使用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); 
?> 

另外,它也可以有這樣的字符串? '[email protected]:test test2:test2',而電子郵件將在任何時候在冒號之前。

+0

這幾乎肯定是不恰當的使用正則表達式。當一個值包含一個冒號,一個單引號,一個換行符或任何其他數字的字符在SQL中帶有特殊含義時,你會做什麼? – 2009-11-11 21:02:08

+0

不會有其他數據。我確信這一點。它嚴格偏向於測試:測試 – Homework 2009-11-11 21:03:36

回答

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 ', (' 
+0

@Bart非常感謝。我對此很缺乏經驗,現在我一直在玩它一個小時。 – Homework 2009-11-11 21:21:51

+0

沒問題。只要確保你明白你在做什麼(仔細閱讀我的解釋)。 – 2009-11-11 21:23:15