多行负向超前 - php

我对regex不太满意(我花了几个小时),而且我很难替换2个标识符(“ {|”和“ |}”)之间的所有空行

我的正则表达式看起来像这样(对不起,您的眼睛):(\{\|)((?:(?!\|\}).)+)(?:\n\n)((?:(?!\|\}).)+)(\|\})

(\{\|):字符“ {|”
((?:(?!\|\}).)+):如果不是在“ |}”之后的所有内容(负向超前)
(?:\n\n):我要删除的空行
((?:(?!\|\}).)+):如果不是在“ |}”之后的所有内容(负向超前)
(\|\}):字符“ |}”

Demo

它可以工作,但是只删除最后一个空行,您能帮助我使它与所有空行一起工作吗?

我尝试在\ n \ n上添加一个否定的前瞻性,并在所有内容上重复一个组,但没有成功。

参考方案

几种方法:

基于\G的模式:(仅需要一个模式)

$txt = preg_replace('~ (?: \G (?!\A) | \Q{|\E ) [^|\n]*+ (?s: (?! \Q|}\E | \n\n) . [^|\n]*)*+ \n \K \n+ ~x', '', $txt);

\G匹配字符串的开头或最后一次成功匹配之后字符串中的位置。这样可以确保多个匹配是连续的。

我所说的基于\G的模式可以像这样被模式化:

(?: \G position after a successful match | first match beginning ) reach the target \K target

“到达目标”部分设计为永远不会匹配结束序列|}。因此,一旦找到最后一个目标,\G部分将失败,直到第一个匹配部分再次成功。

~ 
### The beginning
(?:
    \G (?!\A) # contigous to a successful match
  |
    \Q{|\E # opening sequence
           #; note that you can add `[^{]* (*SKIP)` before to quickly avoid 
           #; all failing positions

           #; note that if you want to check that the opening sequence is followed by 
           #; a closing sequence (without an other opening sequence), you can do it
           #; here using a lookahead
)

### lets reach the target
#; note that all this part can also be written like that `(?s:(?!\|}|\n\n).)*`
#; or `(?s:[^|\n]|(?!\|}|\n\n).)*`, but I choosed the unrolled pattern that is
#; more efficient.

[^|\n]*+ # all that isn't a pipe or a newline

# eventually a character that isn't the start of |} or \n\n
(?s:   
    (?! \Q|}\E | \n\n ) # negative lookahead
    . # the character
    [^|\n]*
)*+
#; adding a `(*SKIP)` here can also be usefull if there's no more empty lines
#; until the closing sequence

### The target

\n \K \n+ # the \K is a conveniant way to define the start of the returned match
          # result, this way, only \n+ is replaced (with nothing)
~x

preg_replace_callback :(更简单)

$txt = preg_replace_callback('~\Q{|\E .*? \Q|}\E~sx', function ($m) {
    return preg_replace('~\n+~', "\n", $m[0]);
}, $txt);

demos

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

PHP-将日期插入日期时间字段 - php

我已在数据库中使用datetime字段存储日期,使用PHP将“今天的日期”插入该字段的正确方法是什么?干杯, 参考方案 我认为您可以使用php date()函数

PHP-如何获取类的成员函数列表? - php

如果我知道班级的名字。有没有办法知道类的成员函数列表? 参考方案 get_class_methods()是你的朋友

php-casperjs获取内部文本 - php

我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…