2017-10-11 111 views
0

我有一個字符串數組,例如:字符串數組需要格式化

$testArray = array ('here I am going to have a string that is over 50 charactersss ', 'where I am going to hav string that is over 50 charactersss'); 

我需要基本上創建其中將採取陣列或多個陣列和計數字符串的長度的函數。如果是超過30個字符則它將執行該操作是從數組中刪除的項目,並創建新的線,其不超過30個字符,詞語是完好這樣的字符串:

'here I am going to have a 
string that is over 50 where 
I am going to have a string 
that is over 50 charactersss' 

到目前爲止,我已經玩了幾天,但不能得到這個工作...

這是我已經嘗試我需要一種計數方式,如果數組中的字符串長度超過30,然後我可以應用像這樣:

public function textFunction($content = []) 
{ 
    $rawText  = implode(' ', $content); 
    $cleanText  = trim(preg_replace('/\s\s+/', ' ', 
    str_replace("\n", " ", $rawText))); 
    $formattedText = wordwrap($cleanText, 30, "\n"); 
    return $formattedText; 
}            

以上的工作,但我該如何檢查如果數組中的內容超過30個字符來執行此操作,我將不得不循環內容,但如果這樣做有意義,則無法執行上述操作。

+1

這就是問題的一個很好的說明,但什麼是真正重要的這裏是展示你的嘗試。即使是一個瘋狂的誤導嘗試總比沒有好:它表明你致力於解決問題。 – tadman

+1

使用[wordwrap](http://php.net/manual/en/function.wordwrap.php)。 – FirstOne

+0

這是我試過的,我需要一種計數方式,如果在數組中的字符串長度超過30,那麼我可以應用這樣的事情: – gold82

回答

0

你可以使用一些wordwrap:

$testArray = array ('here I am going to have a string that is over 50 charactersss ', 'where I am going to hav string that is over 50 charactersss'); 

$newarray = []; 
foreach ($testArray as $str) { 
    $newarray = array_merge($newarray,explode("\n",wordwrap($str,30))); 
} 

結果數組(甩):

array(5) { 
    [0]=> 
    string(25) "here I am going to have a" 
    [1]=> 
    string(22) "string that is over 50" 
    [2]=> 
    string(13) "charactersss " 
    [3]=> 
    string(30) "where I am going to hav string" 
    [4]=> 
    string(28) "that is over 50 charactersss" 
} 

例子:http://sandbox.onlinephpfunctions.com/code/8987b80df4cbe9876568e64a9e983a8c3a492606