douyu0845 2013-08-30 10:13
浏览 37
已采纳

在preg_split之后附加多个值

Im running a loop to insert a column from csv file .The csv file contains a column with values like

India
srilanka
china taiwan
USA UK France
china japan

I split the column using preg_split function ,to split based on empty spaces

preg_split('/\s+/', $countries);

After splitting i get the output like this

Array
(
    [0] => India
)
Array
(
    [0] => srilanka
)
Array
(
    [0] => USA
    [1] => UK
    [2] => France
)

Array
(
    [0] => china
    [1] => japan

)

each array if it contains more than one value it should append 2nd and third with opening and closing braces

I want to have final value as

india
srilanka
USA(UK France)
China(japan)
  • 写回答

1条回答 默认 最新

  • dragon202076 2013-08-30 10:33
    关注

    I think this does what you want. This gets each line as argument, not the array. So you don't have to do the preg_split:

    function split_countries($line) {
        $split = explode(" ", $line);
        $ret = array_shift($split);
        if (count($split)) {
            $ret .= "(" . implode(" ", $split) . ")";
        }
        return $ret;
    }
    
    echo split_countries("India") . "
    ";
    echo split_countries("USA UK France") . "
    ";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作