duanba4942 2017-02-28 09:43
浏览 41
已采纳

将PHP中的输入字符串拆分为多个部分而不会破坏单词

have managed to take an input string and split it into two parts and write it to 2 files. What I want to achieve now is the be able to take it when it's bigger than my limit and split it into 3 or even 4 parts and write that data to separate files without breaking the input.

Here's what I have managed so far which I found here at this question: Split Strings in Half (Word-Aware) with PHP

public function createfiles(array $lines)
{
    $File1  = __DIR__ . '/file1.txt';
    $File2  = __DIR__ . '/file2.txt';

    $regexLines = [];

    foreach ($lines as $line) {
        $regexLines[] = preg_quote($line);
    }
    $data = implode('|', $regexLines);

    //current data input is 18000
    $myLimit = 10000;

    $dataLength = strlen($data);

    if ($dataLength > $myLimit) {

        $middle = strrpos(substr($data, 0, floor($dataLength / 2)), '/') + 1;
        //now want to split into four parts if input data is for instance 35000 characters

        // Strip off trailing /
        $data1 = substr($data, 0, $middle-1);
        $data2 = substr($data, $middle);
        //now want a $data3 and $data4 also stripping off a trailing /

        $this->writeToFile($File1, $data1);
        $this->writeToFile($File2, $data2);
        //now want to write to $File3 and $File4 if needed

    } else {
        $this->writeToFile($File1, $data);
    };
}
  • 写回答

1条回答 默认 最新

  • doujiu8178 2017-03-03 13:09
    关注

    Finally found a solution after hours of digging and fiddling. I threw a big list at it and it broke it up nicely into 7 files for me without breaking words in half.

    public function createmultiplefiles(array $lines)
    {
        $regexLines = [];
    
        foreach ($lines as $line) {
            $regexLines[] = preg_quote($line);
        }
        $data = implode('|', $regexLines);
    
        $mylimit = 10000;
        $datalength = strlen($data);
        $lastpos = 0;
    
        for ($x = 1; $lastpos < $datalength; $x++) {
    
            if( ($datalength-$lastpos) >= $mylimit){
                $pipepos = strrpos(substr($data, $lastpos, $mylimit), '|');
                $splitdata = substr($data, $lastpos, $pipepos);
                $lastpos = $lastpos + $pipepos+1;
            }else{
                $splitdata = substr($data, $lastpos);
                $lastpos = $datalength;
            }
            $file = __DIR__ . 'myfile-' . $x . '.txt';
            $this->writeToFile($file, $splitdata);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100