将 PHP 中的输入字符串拆分为多个部分而不破坏单词 [英] Split input string in PHP into multiple parts without breaking words

查看:57
本文介绍了将 PHP 中的输入字符串拆分为多个部分而不破坏单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经设法将输入字符串分成两部分并将其写入 2 个文件.我现在想要实现的是能够在它大于我的限制时将其拆分为 3 甚至 4 部分并将该数据写入单独的文件而不会破坏输入.

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.

这是我到目前为止在这个问题上找到的:使用 PHP 将字符串一分为二(字识别)

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);
    };
}

推荐答案

经过数小时的挖掘和摆弄,终于找到了解决方案.我扔了一个很大的清单,它很好地将它分成了 7 个文件,而没有将单词分成两半.

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);
    }
}

这篇关于将 PHP 中的输入字符串拆分为多个部分而不破坏单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆