0

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 !

5
  • 1
    Why not just explode it now with "\n" as delimiter?! Commented Apr 23, 2015 at 8:52
  • You need to take a shot to regular expressions, and/or DOM functions in PHP. Commented Apr 23, 2015 at 8:52
  • 1
    yes a mix of it explode, you said it right Commented Apr 23, 2015 at 8:52
  • 1
    This may help stackoverflow.com/questions/11254787/… Commented Apr 23, 2015 at 8:56
  • thanks all ! I did that : $str = explode("\n", wordwrap($string, $desired_width)); Commented Apr 23, 2015 at 9:00

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I did that too (5 minutes ago before) :) thanks ! $str = explode("\n", wordwrap($string, $desired_width));
1

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

2 Comments

Huff, good thing OP doesn't have a few asterix in their string!
You need to use any text or symbol that is not expected to exist in the string as split point. the problem appears if the string is dynamic and it contains many stars (in this case) or a new line ' /n' (in the previous solution ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.