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

送分小仙女□ 提交于 2021-02-08 10:17:24

问题


I'm trying to split a string after x characters and put it in array. But I need to don't cut word if x is in a middle of a word. What I expect is to split on the word inferior.

I Tried this :

CODE

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

OUTPUT

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

How to put it in array ? Is there another method to do that ? a mix between this and explode() ? thanks !


回答1:


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



回答2:


Try this

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

the output

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"
}


来源:https://stackoverflow.com/questions/29818232/php-split-string-in-array-after-x-characters-without-cut-word-on-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!