我有一个字符串数组,例如:
$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个字符来执行此操作我必须循环内容但如果有意义则无法执行上述操作。
答案 0 :(得分: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