PHP preg_replace介于2个分隔符之间

时间:2012-02-01 21:04:58

标签: php regex

您好我正在尝试用大括号,中的长字符串替换| [],但以下内容似乎失败了。

这是字符串。

  

ID:3a0dd504341fb10a055xxxxxx,time:Wed Feb 01 12:54:39 EST 2012,client:10.192.34.13,user:User [ID:1456xcvererwe,session ID:sdfweerwer234325433],action:USER_ACTION_ITEM,action id:36014,result :FAIL,原因:USER_EXCEPTION,参数:[abcd,test12,testing]

这就是我想要的输出。

  

ID:3a0dd504341fb10a055xxxxxx,time:Wed Feb 01 12:54:39 EST 2012,client:10.192.34.13,user:User [ID:1456xcvererwe |会话ID:sdfweerwer234325433],操作:USER_ACTION_ITEM,操作ID:36014,结果:失败,原因:USER_EXCEPTION,参数:[abcd | test12 |测试]

我试过了

$text = preg_replace("/(^[)(.*)(])/U","|",$text);

1 个答案:

答案 0 :(得分:0)

使用preg_replace_callback

$text = 'ID: 3a0dd504341fb10a055xxxxxx, time: Wed Feb 01 12:54:39 EST 2012, client: 10.192.34.13, user: User [ID: 1456xcvererwe, session ID: sdfweerwer234325433 ], action: USER_ACTION_ITEM, action id: 36014, result: FAIL, reason: USER_EXCEPTION, arguments: [abcd, test12 , testing ]';

function rep($r){
    return "[". preg_replace('/\s*,\s*/',' | ', $r[1]). "]";
}
echo preg_replace_callback('/\[([^\]]+)\]/i', 'rep', $text);