Split PHP String line-by-line
Usually, you can just explode("\n")
, but some systems use "\r\n"
or "\n\r"
(actually, I don't think this one is used). So if you're getting documents or text from various systems (as you might on the web), you might want a more robust version than just splitting by "\n"
, as you probably don't want extra "\r"
hanging around. I think "\n"
is "new line" and "\r"
is carriage return (i.e. pressing enter), but I'm not sure.
You can also do it with regex, but years ago when I tested, this was signficantly faster.
$arrayOfLines = explode("\n",
str_replace(["\r\n","\n\r","\r"],"\n",$str)
);