1

简而言之
,给定一个这样的字符串 -

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

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

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;s -

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

3 回答 3

1

尝试这个:

$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_»
-->
于 2012-05-08T09:44:54.893 回答
1

我想您忘记了源中的“或”运算符(位于第三个 MAX_ 之前)。有替代品。正则表达式的版本 - 它更通用(因为它可以匹配并安全地替换 'and' 和 'or' 运算符)并且它经过了一些优化(因为它不使用前瞻/后视语法):

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

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

于 2012-05-08T10:01:44.913 回答
0

怎么样:

$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)
于 2012-05-08T10:04:54.587 回答