按段落的字符拆分为 PHP 中的 3 个相等部分

Split by characters of a paragraph into 3 equal parts in PHP

如果我有一个段落,我需要将它分成 3 个相等的部分(按字符)。

这是我的字符串

$string="this is my long text this is my long text this 
         is my long text this is my long text 
         this is my long text this is my 
         long text this is my long text this is my long text
         this is my long text  this is my long text";

我需要的是:

有专家吗?

您可以通过如下编码实现您的要求:

$string="this is my long text this is my long text this 
     is my long text this is my long text 
     this is my long text this is my 
     long text this is my long text this is my long text
     this is my long text  this is my long text";


$strlen = strlen($string);



$strlen1 = floor((35 / 100) * $strlen);
$strlen2 = $strlen1 + floor((35 / 100) * $strlen);
$strlen3 = $strlen2 + floor((30 / 100) * $strlen);

echo substr($string,0,$strlen1);
echo"<br>";
echo substr($string,$strlen1,$strlen2);
echo "<br>";
echo substr($string,$strlen2,$strlen3);

为了更好地使用您可以将其包装在 returns 拆分字符串的函数中:)

<?php 
$string = "this is my long text this is my long text this 
     is my long text this is my long text 
     this is my long text this is my 
     long text this is my long text this is my long text
     this is my long text  this is my long text";
$arr1   = str_split($string);

$pieces = array_chunk($arr1, ceil(count($arr1) / 3));
echo explode($pieces[0],'');// this will convert the array back into string you wish to have.
echo explode($pieces[1],'');
echo explode($pieces[2],'');


?>

我还没有测试过。但是这样我们就可以做到。 首先将字符串拆分为数组,然后用 array_chunk.

分成你想要的一半

现在,如果您打印 $pieces。您将在每个索引中获得切片输入。

也检查这个

$string="this is my long text this is my long text this 
         is my long text this is my long text 
         this is my long text this is my 
         long text this is my long text this is my long text
         this is my long text  this is my long text";

 $strlen=strlen($string);

 $first= intval($strlen * (35/100));
 $second=intval($strlen * (35/100));
 $third=intval($strlen * 30/100);



$first_part=substr($string,0,$first);
$second_part=substr($string,$first,$second);
$third_part=substr($string,($first+$second));

使用mb_strlen()mb_substr()函数的解决方案:

$chunk_size = round(mb_strlen($string) * 0.35);
$parts = [];
foreach ([0, $chunk_size, $chunk_size * 2] as $pos) {
    $parts[] = mb_substr($string, $pos, $chunk_size);
}
print_r($parts);

输出:

Array
(
    [0] => this is my long text this is my long text this
         is my long text this is my lon
    [1] => g text
         this is my long text this is my
         long text this is my long tex
    [2] => t this is my long text
         this is my long text  this is my long text
)