php regex multiline match

Two modifiers are involved in php multiline regex expression: m and s. Specifically, the m modifier has influence on the interpretation of  the ^ and $ symbols while the s modifier has influence on the dot symbol in the regular expression.

By default, the ^ symbol indicates the beginning of the whole subject string while the $ symbol indicates the end of the whole subject string, even there are newlines(\n) in between the subject string. So,

echo preg_replace("#\\..+$#","","myprogrammingnotes.com\ngoogle.com");
//myprogrammingnotes.com\ngoogle

Since the dot symbol does not match newline by default, we cannot remove the “.com” in  “myprogrammingnotes.com”. To match across multiple lines, we can use the following code:

echo preg_replace("#\\..+$#s","","myprogrammingnotes.com\ngoogle.com");
//myprogrammingnotes

With the s modifier, the php regex matches multiple lines of the subject string. This is true even you use the ungreedy indicator ? because $ only means the end of the while string, not the end of each line.

echo preg_replace("#\\..+?$#s","","myprogrammingnotes.com\ngoogle.com");
//myprogrammingnotes

The correct php regex multiline pattern is:

echo preg_replace("#\\..+?$#ms","","myprogrammingnotes.com\ngoogle.com");
//myprogrammingnotes
//google

Now, the “.com” in every line of the subject is matched and deleted because with the m modifier, the ^ and $ mean the beginning and the end of every line, respectively, and we used ungreedy match.

If you use greedy match,

echo preg_replace("#\\..+$#ms","","myprogrammingnotes.com\ngoogle.com");
//myprogrammingnotes

the php multiline regex replaces all characters from the first dot to the end of the string because the dot symbol now matches the newline.

Next time, when you use preg_match or preg_match_all for multiline string, consider to use the s and m modifiers.

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Leave a Reply