大家好!
最近遇到一個問題,如果在正規搜尋中,使用" . ",也就是代表任意字,會發現任意字並不包含 換行,這時候,我找到一個解決方案
 
 
也就是加上s 這參數即可
請參考以下範例
 
$content = "
Hello!!
Kitty!!
";

//一般情況
echo preg_replace('/Hello.*Kitty/','Hello World',$content);//依然是 Hello!! Kitty!!

//加上S
echo preg_replace('/Hello.*Kitty/s','Hello World',$content);//變成 Hello World!!


 
 
官方網站有說明:
 
s (PCRE_DOTALL)
If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.
 
也就是如果加上s這參數,換行也會算在任意字元裡面。
 
給大家參考囉!感恩。