2017-01-05 63 views
0

如果我有段落,我需要它將它分成3個相等部分(按字符)。將段落中的字符拆分爲3個相等部分,使用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"; 

我需要的是:

    3個部分或第一部分
  • 35%,在第2部分的35%,並在第三部分30%
  • 平等字符( 3部分 - 按字符而不是字或字符串)

任何專家?

+0

你試過實現一個自己的解決方案? –

+0

**空格**將被考慮與否? –

+0

使用** chunk_split **。 – Dave

回答

1

入住這其中也

$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)); 
+1

不錯的東西,你用intval兄弟:) –

+1

正是我想要的東西 – condition0

0

你可以實現你所說的編碼要求如下:

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

爲了更好的使用你可以用它在函數返回字符串劈裂:)

0
<?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分成你想要的一半數。

現在,如果您打印該$件。您將在每個索引中獲得切片輸入。

1

使用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 
) 
相關問題