I agree with the PHP Modifiers Reference in the 'm' modifier description that says:
When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end.
I'm learning regular expressions and this example is a little confusing:
<?php echo preg_replace("/^[\s]*$/m","<p>","with.\n\n\n\t \nTherefor"); ?>
It ends up with:
"with.\n
\nTherefor"
But I put mentally the '^' and '$' metacharacters like previously said. (^,$=imaginal positions)
^with.$\n^$\n^$\n^\t $\n^Therefor$
And reading the regex:
A start of line followed or not by one space character ([ \t\r\n]) followed by the end of the line.
But the regex engine takes from the second '^' to the fourth '$', eating up the '\n'. Shouldn't it be like this?:
(^,$=imaginal positions)
^with.$\n <br/> ^(no space character)$\n <br/> ^(no space character)$\n <br/> ^(\t )$\n <br/> ^Therefor$ with.\n <br/> <p>\n <br/> <p>\n <br/> <p>\n <br/> Therefor
It is supposed that the regex runs toward the right. Why does the regex seem lookahed the '\n'?
Because it matches at the point ^(no space character)$ and then follows...' \n '.
This regex seems to combine multiple lines...
But you can avoid this, by using the U
modifier xor adding a ?
to *
, so that it's not longer greedy:
echo preg_replace("/^[\s]*$/mU","<p>","with.\n\n\n\t \nTherefor");
echo preg_replace("/^[\s]*?$/m","<p>","with.\n\n\n\t \nTherefor");