PHP Regular Expressions Multiline
Description
We have the dollar $ and caret ^ symbols, which mean "end of line" and "start of line," respectively.
Consider the following string:
$multitest = "This is \na test \nfrom \njava2s\n.com";
In order to parse multiline strings, we need the m modifier, and m goes after the final slash.
Note
Without the m modifier, the $ and ^ metacharacters only match the start and end of the entire string.
By adding "m" to the regexp, we're asking PHP to match $ and ^ against the start and end of each line wherever the newline (\n) character is.
Example
All of these code snippets return true:
<?PHP//www . ja va 2s.co m
$multitest = "This is \na test \nfrom \njava2s\n.com";
echo preg_match("/is$/m", $multitest); // returns true if 'is' is at the end of a line
echo "\n";
echo preg_match("/the$/m", $multitest); // returns true if 'the' is at the end of a line
echo "\n";
echo preg_match("/ he/m", $multitest); // returns true if 'the' is at the end of a line
echo "\n";
echo preg_match("/is$/m", $multitest); // returns true if 'is' is at the end of a line
echo "\n";
echo preg_match("/the$/m", $multitest); // returns true if 'the' is at the end of a line
echo "\n";
echo preg_match("/^the/m", $multitest); // returns true if 'the' is at the end of a line
echo "\n";
echo preg_match("/^Symbol/m", $multitest); // returns true if 'Symbol' is at the start of a line
echo "\n";
echo preg_match("/^[A-Z][a-z]{1,}/m", $multitest); // returns true if there's a capital and one or more lowercase letters at line start
echo "\n";
echo preg_match("/^[A-Z][a-z]{1,}/m", $multitest); // returns true if there's a capital and one or more lowercase letters at line start
?>
The code above generates the following result.
Example 2
If you want to get the start and end of the string when m is enabled, you should use \A and \z, like this:
<?PHP/*from w w w.j a va2s .c om*/
echo preg_match("/\AThis/m", $multitest); // returns true if the string starts with "This" (true)
echo "\n";
echo preg_match("/symbol\z/m", $multitest); // returns true if the string ends with "symbol" (false)
?>
The code above generates the following result.