2015-02-09 114 views
0

替換字符串我有這類型的作品在一個.txt文件正則表達式查找和PHP

rpad(lookup_ext([DM_W1_XREF.DM_W1_XREF.XREF_VKORG_VTWEG, \'PRE_LOAD_CACHE\', \'MAX\'], [ VKORG_NEW ], [ NULL ], [ SYSTEM_NAME, \'=\', T_M67_A033_EXT.SYSTEM_NAME, VKORG_OLD, \'=\', T_M67_A033_EXT.VKORG ]) 
SET("output_cols_info" = \'<?xml version="1.0" encoding="UTF-8"?><output_cols_info><col index="1" expression="no"/> 
</output_cols_info>\', "run_as_separate_process" = \'no\'), 4, \' \') 

我想這些將被轉換爲

nvl(rpad(lookup_ext([DM_W1_XREF.DM_W1_XREF.XREF_VKORG_VTWEG, \'PRE_LOAD_CACHE\', \'MAX\'], [ VKORG_NEW ], [ NULL ], [ SYSTEM_NAME, \'=\', T_M67_A033_EXT.SYSTEM_NAME, VKORG_OLD, \'=\', T_M67_A033_EXT.VKORG ]) 
SET("output_cols_info" = \'<?xml version="1.0" encoding="UTF-8"?><output_cols_info><col index="1" expression="no"/> 
</output_cols_info>\', "run_as_separate_process" = \'no\'), 4, \' \'),'$$$$') 

我怎樣才能做到這一點與PHP?新增加的$應該和數字4一樣多。

回答

0

這可以通過preg_replace_callback函數來實現。

$str= <<< EOT 
rpad(lookup_ext([DM_W1_XREF.DM_W1_XREF.XREF_VKORG_VTWEG, \'PRE_LOAD_CACHE\', \'MAX\'], [ VKORG_NEW ], [ NULL ], [ SYSTEM_NAME, \'=\', T_M67_A033_EXT.SYSTEM_NAME, VKORG_OLD, \'=\', T_M67_A033_EXT.VKORG ]) 
SET("output_cols_info" = \'<?xml version="1.0" encoding="UTF-8"?><output_cols_info><col index="1" expression="no"/> 
</output_cols_info>\', "run_as_separate_process" = \'no\'), 4, \' \') 
EOT; 
echo preg_replace_callback("~(?s)rpad\(.*?,\h*(\d+),\h*\\\\'\h*\\\\'\)~", function($m){ 
    return 'nvl('.$m[0].",'".str_repeat("$", $m[1])."')"; 
} 
    , $str); 

輸出:

nvl(rpad(lookup_ext([DM_W1_XREF.DM_W1_XREF.XREF_VKORG_VTWEG, \'PRE_LOAD_CACHE\', \'MAX\'], [ VKORG_NEW ], [ NULL ], [ SYSTEM_NAME, \'=\', T_M67_A033_EXT.SYSTEM_NAME, VKORG_OLD, \'=\', T_M67_A033_EXT.VKORG ]) 
SET("output_cols_info" = \'<?xml version="1.0" encoding="UTF-8"?><output_cols_info><col index="1" expression="no"/> 
</output_cols_info>\', "run_as_separate_process" = \'no\'), 4, \' \'),'$$$$') 
+0

感謝ü洙多。其工作:D – Tirumalesh 2015-02-09 06:57:37

0

有可能有許多的技術來實現你的目標。

這是最簡單的,你的正則表達式可能是你的正則表達式

rpad(.*?)\\'\s\\\\'\) 

而且這可能是你替換字符串

rpad(val\1,'$$$$') 

享受