正则表达式在模式之间添加一些东西,同时保留两者之间的模式


Regular expression adding something in between patterns, while preserving the patterns in between

简介
给定这样的字符串 -

MAX_checkTime_Hour('0,1', '=~') and (MAX_checkTime_Day('1,2', '=~') or MAX_checkTime_Day('1,2', '=~')) and MAX_checkGeo_Country('DZ,AO,BJ)

我想在and MAX_and (MAX_and ((MAX_等模式之前和之间插入<br />标签,以便输出是 -

MAX_checkTime_Hour('0,1', '=~')<br /> and <br />(MAX_checkTime_Day('1,2', '=~') or MAX_checkTime_Day('1,2', '=~'))<br /> and <br />MAX_checkGeo_Country('DZ,AO,BJ)

到目前为止
我做了什么有了下面的正则表达式替换,我几乎就在那里。插入<br />标签是有效的,但我必须插入固定数量的&nbsp; -

preg_replace("/'s+and's+MAX_/",'<br />&nbsp;&nbsp;&nbsp;and&nbsp;&nbsp;&nbsp;<br />MAX_',$str);

我想——

  • 保留空格的确切数量。
  • 保留MAX_之前第一个括号的确切数量。

所以,如果原始字符串是这样的——

MAX_checkTime_Hour('0,1', '=~') <3 white spaces here> and <5 white spaces here> #2 first brackets here#MAX_checkTime_Day('1,2', '=~')

我希望输出是 -

MAX_checkTime_Hour('0,1', '=~')<br /> <3 white spaces here> and <5 white spaces here> <br /><first brackets here>MAX_checkTime_Day('1,2', '=~')

更新
我尝试了以下内容,假设可变数量的空格将存储在变量中,但它不起作用 -

preg_replace("/{'s+}and{'s+}MAX_/",'<br />$1and$2<br />MAX_',$str);

我想你忘记了源中的"or"运算符(位于第三个MAX_之前)。正则表达式的alt.版本-它更通用(因为它可以匹配并安全地替换"and"和"or"运算符),并且进行了更多的优化(因为它不使用前瞻/后视语法):

$result = preg_replace('/('s+(and|or)'s+)('(*MAX_)/', '<br/>$1<br/>$2', $str);

此外,它与 DRY 兼容,替换字符串不包含源字符串的任何部分

试试这个:

$result = preg_replace('/(?<=and)(?=['s(]+MAX_)/im', '<br />and<br />MAX_''', $subject);

正则表达式解释

<!--
(?<=and)(?=['s'(]+MAX_)
Options: case insensitive; ^ and $ match at line breaks
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=and)»
   Match the characters “and” literally «and»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=['s'(]+MAX_)»
   Match a single character present in the list below «['s'(]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      A whitespace character (spaces, tabs, and line breaks) «'s»
      A ( character «'(»
   Match the characters “MAX_” literally «MAX_»
-->

怎么样:

$str = "MAX_checkTime_Hour('0,1', '=~') and (MAX_checkTime_Day('1,2', '=~') or MAX_checkTime_Day('1,2', '=~')) and MAX_checkGeo_Country('DZ,AO,BJ)";
echo preg_replace("/('s+)and('s+)('(*MAX_)/", "<br />$1and$2<br />$3", $str);

输出:

MAX_checkTime_Hour('0,1', '=~')<br /> and <br />(MAX_checkTime_Day('1,2', '=~') or MAX_checkTime_Day('1,2', '=~'))<br /> and <br />MAX_checkGeo_Country('DZ,AO,BJ)