I have a function that uses comma as separator in breaking name/email pairs from a long string. I would like to modify this function to be able to detect if instead of a comma a line break is used. Here's the function that needs to be modified:
$str = '"Fname Lname" <abc@email.com>, abc@gmail.com';
$pairs = explode( ",", $str );
foreach( $pairs as $pair ) {
if( strpos($pair, '<') ) {
$output = explode( "<", $pair );
$output['0'] = trim( str_replace( "\"", "", $output['0'] ) );
$output['1'] = trim( rtrim( $output['1'], ">" ) );
} else {
$output = array();
$output['0'] = '';
$output['1'] = $pair;
}
print_r($output); // Save it to database here
}
I found a post suggesting using a file() fnction but I am not sure how to combine those two together.
$str = '"Fname Lname" <abc@email.com>, abc@gmail.com';
$pairs = file($str, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
Try this, convert to line breaks then check if exists
$str=nl2br($str);
if (strpos($str,'<br />')!==false){
$pairs = array_filter(explode( "<br />", $str ));
}
Or alternatively, you can break apart on spaces which should catch the line breaks
if (strpos($str,' ')!==false){
$pairs = array_filter(explode( " ", $str ));
}
Note; I added the array_filter because it will remove empty values for you. Also, I would suggest using the FILTER_VALIDATE_EMAIL from here http://php.net/manual/en/filter.filters.validate.php before adding to your database.
A true linebreak in php is written as " "
. Simply use
$pairs = explode( "
", $str );
Note that the \
changes behavior for the n
, thus making it a line break. " "
gives a nice line while "\ "
gives as output.