PHP - 在 X 个字符后拆分数组中的字符串,不限制切词

PHP - Split string in array after X characters without cut word on limit

我试图在 x 个字符后拆分一个字符串并将其放入数组中。但是如果 x 在一个单词的中间,我不需要删掉单词。我期望的是在劣势这个词上分裂。

我试过了:

代码

$string = "Helllooooo I'mmm <strong>theeeeee</strong> <em> woooooorrd</em> theeee loooonnngessttt";
$desired_width = 24;

$str = wordwrap($string, $desired_width, "\n");

var_dump($str);
die;

输出

string 'Helllooooo I'mmm
<strong>theeeeee</strong>
<em> woooooorrd</em>
theeee loooonnngessttt' (length=86)

如何放入数组中?还有另一种方法吗? this 和 explode() 之间的混合?谢谢!

$string = "Helllooooo I'mmm <strong>theeeeee</strong> <em> woooooorrd</em> theeee loooonnngessttt";
$desired_width = 24;

$str = wordwrap($string, $desired_width, "\n");
$arr = explode("\n", $str);
var_dump($arr);
die;

试试这个

$string = "Helllooooo I'mmm <strong>theeeeee</strong> <em> woooooorrd</em> theeee loooonnngessttt";
$desired_width = 24;

$str = wordwrap($string, $desired_width, "***");
$str = explode("***",$str);
var_dump($str);
die;

输出

array(4) {
  [0]=>
  string(16) "Helllooooo I'mmm"
  [1]=>
  string(25) "<strong>theeeeee</strong>"
  [2]=>
  string(20) "<em> woooooorrd</em>"
  [3]=>
  string(22) "theeee loooonnngessttt"
}