dongzhuandian3292 2012-05-20 14:55
浏览 86
已采纳

添加换行符作为分隔符

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); 
  • 写回答

2条回答 默认 最新

  • duanjupiao4730 2012-05-20 15:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭