0

Using wordwrap so that I can get whole words, how can I split a string of upto 255 characters into two line variables of 45 characters and ignore the rest?

I would use:

$line1 = substr($str, 0, 45);
$line2 = substr($str, 45, 45);

But I need the break to be a a word, not the 45th character.

Warren
  • 1,984
  • 3
  • 29
  • 60
  • Possible duplicate of [PHP: split a long string without breaking words](https://stackoverflow.com/questions/11254787/php-split-a-long-string-without-breaking-words) – dipak_pusti Dec 29 '17 at 06:51
  • Agreed, but I must say that my question and the answer I'm waiting to accept are very succinct. – Warren Dec 29 '17 at 06:52

3 Answers3

1

You can use wordwrap,

$lines = explode("\n", wordwrap($str, 45, "\n"));
Abey
  • 1,408
  • 11
  • 26
0

php wardwrap is the function you should try.

wordwrap

$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 45, "<br />\n");

echo $newtext;

Or by using both explode and wordwrap,

$x = 15;
$longString = 'I like apple. You like oranges. We like fruit. I like meat, also.';
$lines = explode("\n", wordwrap($longString, $x));

var_dump($lines);
array(6) {
  [0]=>
  string(13) "I like apple."
  [1]=>
  string(8) "You like"
  [2]=>
  string(11) "oranges. We"
  [3]=>
  string(13) "like fruit. I"
  [4]=>
  string(10) "like meat,"
  [5]=>
  string(5) "also."
}

You can now use first 2 values from array.

dipak_pusti
  • 1,645
  • 2
  • 23
  • 42
0

You can find the space after or before the 45th character with strpos(string,find,start) like strpos($string, " ", 45). Or find all delimiter (space,"!","." etc) characters with regex and then carry on the query according to maths.

$subject = "abcdef sdfasdfa hdfghdfgh...";
$pattern = '/[\s\n\b!.]/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 45);
print_r($matches);

But take into consideration that it will cut, for example until 51th character if it finds the delimiter there.

dipak_pusti
  • 1,645
  • 2
  • 23
  • 42
Nagibaba
  • 4,218
  • 1
  • 35
  • 43