简体   繁体   English

正则表达式与换行符不匹配

[英]Regex doesn't match line break

One of these days where I'm about to question my sanity again... 有一天,我将再次质疑我的理智......

I don't understand why my regex refuses to match for the optional line break. 我不明白为什么我的正则表达式拒绝匹配可选的换行符。 Code: 码:

$string = 'this is some template {$code}. nice! 
{$varinnewline}
{if $bla}1{else}2{/if}
';

echo "<pre>";
preg_replace_callback("/\{([^\}]*)\}(\r\n)?/Us", function($matches) {
  print_r($matches);
}, $string);

It produces (among others) this output: 它产生(以及其他)此输出:

Array
(
    [0] => {$varinnewline}
    [1] => $varinnewline
)

and not this (which it does if I remove the 0-1 match ? at the end of the regex): 而不是这个(如果我在正则表达式的末尾删除0-1匹配?它会这样做):

Array
(
    [0] => {$varinnewline}

    [1] => $varinnewline
    [2] => 
)

Basically I want a regex that matches the \\r\\n at the end of the line if it is available. 基本上我想要一个与行末尾的\\ r \\ n匹配的正则表达式(如果可用)。 (I need that because after transforming the {} into < ?php ?> the new line after the ?> seems to be removed by the php interpreter) (我需要这个,因为在将{}转换为<?php?>之后,新的行在?>之后似乎被php解释器删除了)

See a post I answered awhile back explaining this. 看一篇帖子我回答了一段时间后再解释一下。

But to answer your question, apart from \\r and \\n PCRE also has another character group matching newlines, you can use a nifty escape sequence for this case which is \\R . 但是要回答你的问题,除了\\r\\n PCRE还有另一个匹配换行符的字符组,你可以使用一个漂亮的转义序列来解决这个案例\\R

\\R matches a generic newline; \\R匹配通用换行符; that is, anything considered a linebreak sequence by Unicode. 也就是说,任何被Unicode视为换行序列的东西。 This includes all characters matched by \\v (vertical whitespace) and the multi character sequence \\x0D\\x0A . 这包括\\v (垂直空白)和多字符序列\\x0D\\x0A匹配的所有字符。

preg_replace_callback("~\{([^\}]*)\}(\R)?~", function($matches) {
    print_r($matches);
}, $string);

Output 产量

Array
(
    [0] => {$code}
    [1] => $code
)
Array
(
    [0] => {$varinnewline}

    [1] => $varinnewline
    [2] => 

)
Array
(
    [0] => {if $bla}
    [1] => if $bla
)
Array
(
    [0] => {else}
    [1] => else
)
Array
(
    [0] => {/if}

    [1] => /if
    [2] => 

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM