How do you split a text field/textarea by line breaks?
Sometimes you want to provide a simple way for users to enter multiple values. Perhaps the simplest way for the user is to understand is allow them to enter new values on each line. Historically that’s how Internet Explorer allowed you to configure multiple home pages: 1 per line. It’s a tested method that works.
However, how do you then process the information? There are lots of possiblitities, however I prefer an answer I found was posted back in 2011: Use preg_split().
preg_split( '/\r\n|[\r\n]/', $_POST[ 'yourtextarea' ], PREG_SPLIT_NO_EMPTY )
By using regex, this function will handle entries from various platforms. You don’t need to worry about whether is just a carriage return or just a linefeed or even both at the end of a line. The split is handled nicely and you get an array returned. It will even, by adding an optional third parameter, ignore any blank lines. Once you have your value returned, you can write the array out to an option record, or process it however you like.
Once you have the array loaded from your DB, how do you split it into multiple lines again? That’s simple: Use implode().
implode( "\n", $myarray );
Hope that helps someone!