Skip to content

Instantly share code, notes, and snippets.

@danieltome
Created April 8, 2015 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieltome/1235a560182ec7ddac45 to your computer and use it in GitHub Desktop.
Save danieltome/1235a560182ec7ddac45 to your computer and use it in GitHub Desktop.
PHP to split text into lines without breaking the words
<pre>
<?php
$strings = array(
'I pay tribute to those who have carried the anzac spirit',
'I pay tribute to my friend capt first last',
'I pay tribute to my friend capt first name last name',
'I pay tribute to the anzacs',
'I pay tribute to my great grandmother capt. first last',
);
for ($i=0; $i<count($strings); $i++) {
//$word_break_result = preg_replace('/([^\s]{17})/', "$1\n", $strings[$i]);
$word_break_result = wordwrap($strings[$i], 17, "\n");
print_r($word_break_result);
print "\n\n";
$lines_arr = split("\n", $word_break_result);
var_dump($lines_arr);
print "<hr>";
}
@danieltome
Copy link
Author

Outputs:
I pay tribute to
those who have
carried the anzac
spirit

array(4) {
[0]=>
string(16) "I pay tribute to"
[1]=>
string(14) "those who have"
[2]=>
string(17) "carried the anzac"
[3]=>
string(6) "spirit"
}
I pay tribute to
my friend capt
first last

array(3) {
[0]=>
string(16) "I pay tribute to"
[1]=>
string(14) "my friend capt"
[2]=>
string(10) "first last"
}
I pay tribute to
my friend capt
first name last
name

array(4) {
[0]=>
string(16) "I pay tribute to"
[1]=>
string(14) "my friend capt"
[2]=>
string(15) "first name last"
[3]=>
string(4) "name"
}
I pay tribute to
the anzacs

array(2) {
[0]=>
string(16) "I pay tribute to"
[1]=>
string(10) "the anzacs"
}
I pay tribute to
my great
grandmother capt.
first last

array(4) {
[0]=>
string(16) "I pay tribute to"
[1]=>
string(8) "my great"
[2]=>
string(17) "grandmother capt."
[3]=>
string(10) "first last"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment