PHP's preg_replace regex that matches multiple lines

前端 未结 2 1347
死守一世寂寞
死守一世寂寞 2020-12-01 18:13

How do I create a regex that takes into account that the subject consists of multiple lines?

The \"m\" modifier for one does not seem to work.

相关标签:
2条回答
  • 2020-12-01 18:56

    Try the 's' modifier. Meaning 'treat as if a single line'.

    'm' enables the use of ^ and $ line beginnings and endings to be used.

    0 讨论(0)
  • 2020-12-01 19:07

    Maxwell Troy Milton King is right, but since his answer is a bit short, I'll post this as well and provide some examples to illustrate.

    First, the . meta character by default does NOT match line breaks. This is true for many regex implementations, including PHP's flavour. That said, take the text:

    $text = "Line 1\nLine 2\nLine 3";
    

    and the regex

    '/.*/'
    

    then the regex will only match Line 1. See for yourself:

    preg_match('/.*/', $text, $match);
    echo $match[0]; // echos: 'Line 1'
    

    since the .* "stops matching" at the \n (new line char). If you want to let it match line breaks as well, append the s-modifier (aka DOT-ALL modifier) at the end of your regex:

    preg_match('/.*/s', $text, $match);
    echo $match[0]; // echos: 'Line 1\nLine 2\nLine 3'
    

    Now about the m-modifier (multi-line): that will let the ^ match not only the start of the input string, but also the start of each line. The same with $: it will let the $ match not only the end of the input string, but also the end of each line.

    An example:

    $text = "Line 1\nLine 2\nLine 3";
    preg_match_all('/[0-9]$/', $text, $matches);
    print_r($matches); 
    

    which will match only the 3 (at the end of the input). But:

    but enabling the m-modifier:

    $text = "Line 1\nLine 2\nLine 3";
    preg_match_all('/[0-9]$/m', $text, $matches);
    print_r($matches);
    

    all (single) digits at the end of each line ('1', '2' and '3') are matched.

    0 讨论(0)
提交回复
热议问题