How to replace a regex pattern with a regex pattern?

感情迁移 提交于 2019-12-23 21:25:24

问题


I'm feeling very silly for not being able to figure this one out, but I just cant figure it. I need to replace a regex string with a pattern, I found two examples of doing it, but they honestly left me more confused than ever.

This is my current attempt:

$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);

But that just replaces the \1 and \2 with blanks. So obviously I'm not getting the entire concept.

What I'm wanting at the end is to change:

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

That comma in a poorly formatted CSV throws off some of my other scripts.


回答1:


You're missing braces, the pattern should look like this:

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



回答2:


The backreferences \1 and \2 in your $replacement are meant to refer to captured groups in $pattern. Captured groups are saved by placing brackets around them ().

Try (I changed your regex delimiters [] to ! pending an answer from comments below):

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

Also note that since you have a trailing comma on your $pattern, if your $string ended in "SIP/CL/61436523277,45" that would not be converted. I'd recommend removing that trailing comma.

Also your current regex will convert "SIP/CL/," to "SIP/CL/|". If that is not your intent, change the * after the \d (ie 0 or more matches) to a + (one or more matches).




回答3:


I think you need this:

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

The parens - () - capture the match inside, allowing you to reference it in your replacement pattern.

You could also simplify the replacement pattern by expanding the captures in the match pattern:

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



回答4:


I did this

$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);


来源:https://stackoverflow.com/questions/8903547/how-to-replace-a-regex-pattern-with-a-regex-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!