简体   繁体   中英

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

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 !

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM