2014-02-10 92 views
1

替換它,我想在字符串XXX的preg_match/preg_replace函數在PHP用於匹配模式和在PHP

輸入替換值:

insert into employees values('shrenik', 555, NULL) 

輸出:

insert into employees values('XXX', XXX, NULL) 

我試過了:([0-9]|\'.*\')

我想先匹配insert into,之後想跳過字符串最多(。我在聲明中已經提到了我需要的模式和輸出。

在此先感謝。

回答

0

您可以使用此:

$sql = 'insert into employees values(\'shrenik\', 555, NULL)'; 
$pattern = '~(?:\binsert into [^(]*\(|\G(?<!^),(?:\s*+NULL,)*)\s*+\K(\')?(?(1)[^\']*\'|(?!NULL\b)[^\s,)]*)~i'; 

$sql = preg_replace($pattern, '$1XXX$1', $sql); 

圖案的詳細資料

~       # pattern delimiter 
(?:       # non capturing group: where the pattern is allowed to start 
    \binsert into [^(]*\( # after "insert to" until the opening parenthesis 
    |       # OR 
    \G(?<!^),    # after a precedent match if there is a comma 
    (?:\s*+NULL,)*   # skip NULL values 
)       
\s*+      # zero or more spaces 
\K       # reset all that was matched before from match result 
(')?      # optional capture group 1 with single quote 
(?(1)      # IF capture group 1 exists: 
    [^']*'     # THEN matches all characters except ' followed by a literal ' 
    |       # ELSE 
    (?!NULL\b)[^\s,)]*  # matches all characters except spaces, comma,) and the last NULL value 
)       # ENDIF 
~i       # closing pattern delimiter, case-insensitive 
+0

我試過,但它不工作。 :-( – Shrenik

+0

@ user3292757:我做了一些改變,現在它可以正常工作(測試),你是否嘗試過最後一個版本? –

+0

是的先生我已經嘗試過了,它出錯了,我對於正則表達式是全新的,我正在嘗試在http://www.compileonline.com/上也有同樣的內容。你可以使用代碼 – Shrenik