如何用正则表达式模式替换正则表达式模式?

时间:2012-01-18 00:18:01

标签: php regex csv match

我觉得因为无法解决这个问题而感到非常愚蠢,但我无法想象。我需要用模式替换正则表达式字符串,我找到了两个这样做的例子,但他们老实说让我比以前更加困惑。

这是我目前的尝试:

$string = '26 14:46:54",,"2011-08-26 14:47:02",8,0,"BUSY","DOCUMENTATION","1314370014.18","","","61399130249","7466455647","from-internal","""Oh Snap"" <61399130249>","SIP/1037-00000014","SIP/CL-00000015","Dial","SIP/CL/61436523277,45","2011-08-26 14:47:06","2011-08-26 14:47:15","2011-08-26 ';
$pattern = '["SIP/CL/\d*?,\d*?",]';
$replacement = '"SIP/CL/\1|\2",';
$string = preg_replace($pattern, $replacement, $string);
print($string);

但这只是用空格替换\1\2。显然,我没有得到整个概念。

我最终想要的是改变:

this: "SIP/CL/61436523277,45"
to: "SIP/CL/61436523277|45"

格式不佳的CSV中的逗号会丢弃我的其他一些脚本。

4 个答案:

答案 0 :(得分:2)

你缺少大括号,模式应如下所示:

$pattern = '["SIP/CL/(\d*),(\d*)",]';

答案 1 :(得分:2)

我认为你需要这个:

$pattern = '["SIP/CL/(\d+),(\d+)",]';

parens - () - 捕获内部的匹配,允许您以替换模式引用它。

您还可以通过扩展匹配模式中的捕获来简化替换模式:

$pattern = '[("SIP/CL/\d+),(\d+",)]';   
$replacement = '\1|\2';

答案 2 :(得分:2)

\1中的反向引用\2$replacement旨在引用$pattern捕获的群组。通过在()周围放置括号来保存捕获的组。

尝试(我将您的正则表达式分隔符[]更改为!,等待以下评论的答案):

$pattern = '!"SIP/CL/(\d*?),(\d*?)",!';
$replacement = '"SIP/CL/\1|\2",';

另请注意,由于您的$pattern上有逗号,因此$string结尾的"SIP/CL/61436523277,45"将无法转换。我建议删除那个尾随的逗号。

此外,您当前的正则表达式会将"SIP/CL/,"转换为"SIP/CL/|"。如果这不是您的意图,请将*(即0个或多个匹配项)后的\d更改为+(一个或多个匹配项)。

答案 3 :(得分:0)

我做了这个

$string = '26 14:46:54",,"2011-08-26 14:47:02",8,0,"BUSY","DOCUMENTATION","1314370014.18","","","61399130249","7466455647","from-internal","""Oh Snap"" <61399130249>","SIP/1037-00000014","SIP/CL-00000015","Dial","SIP/CL/61436523277,45","2011-08-26 14:47:06","2011-08-26 14:47:15","2011-08-26 ';
$pattern = '/SIP\/CL\/([0-9]+),([0-9]+)/';
$replacement = 'SIP/CL/\1|\2';
$string = preg_replace($pattern, $replacement, $string);
print($string);