Please wait

Multiline Mode

Strings are not always going to contain one line of characters. Your strings may be broken into multiple lines. For example, take the following:

$str = "1st place: Winnie
2nd place: Piglet
3rd place: Eeyore";

Let's say we wanted to grab a number from each line only if it begins with a number.

preg_match_all("/^\d/", $str, $matches);

The expression we've written tells the program to grab a digit if the string begins with a number. This example only produces one result, which is 1. The other numbers don't get included.

What is multiline mode?

Multiline mode in regular expressions allows the start (^) and end ($) anchors to match the beginning and end of each line within a text rather than just the beginning and end of the entire string.

This means that if the pattern is applied to a multiline string, the anchors will function at the start and end of each line, not just at the very start and end of the string. This behavior can be activated by using the m modifier in the regular expression. It's useful when working with text that contains line breaks, and you want to apply the pattern to each line individually.

If we update our expression like so:

preg_match_all("/^\d/m", $str, $matches);

All numbers from our string are found that start at the beginning of each new line.

Checking the end of a string

We can use multiline mode with the $ anchor.

The following regular expression, \d$, finds the last digit in every line.

$str = "Winnie: 1
Piglet: 2
Eeyore: 3";
preg_match_all("/\d$/m", $str, $matches);

Without the flag m, the dollar $ would only match the end of the whole text, so only the very last digit would be found.

Key Takeaways

  • The m modifier is used to enable multiline mode in a regular expression in PHP.
  • It's helpful when you want to apply a pattern to each line of a multiline string, such as when parsing text documents with line breaks.
  • In multiline mode, the ^ anchor matches the start of each line, and the $ anchor matches the end of each line.


Please read this before commenting