簡體   English   中英

使用preg_replace格式化

[英]Using preg_replace to format

圖案和更換時遇到麻煩。 我怎樣才能使替代品成為最終產品,例如

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'而電子郵件始終在冒號之前。

嘗試這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM