php - Split a string by number of chars without splitting a word

Solution:
I don't think there's a single built-in function that will do it for you, but you could do something like this:
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nec elit dui, nec fermentum velit. Nullam congue ipsum ac quam auctor nec massa nunc.";
$output = array();
while (strlen($string) > 50) {
$index = strpos($string, ' ', 50);
$output[] = trim(substr($string, 0, $index));
$string = substr($string, $index);
}
$output[] = trim($string);
var_dump($output);
// array(3) {
// [0]=>
// string(50) "Lorem ipsum dolor sit amet, consectetur adipiscing"
// [1]=>
// string(55) "elit. Quisque nec elit dui, nec fermentum velit. Nullam"
// [2]=>
// string(43) "congue ipsum ac quam auctor nec massa nunc."
// }
Answer
Solution:
Just go through the string, and after a number (number = 5) of chars check if the next char is a space and split. If there is no space, dont split and go to the next space :-)
Answer
Solution:
I guess i understood you as well, then you can use this function:
<?php
function str_split_len($str, $len)
{
if( $len > strlen($str) )
{
return false;
}
$strlen = strlen($str);
$result = array();
$words = ($strlen / $len);
for( $x = 1; $x <= $len; $x++ )
{
$result[] = substr($str, 0, $words);
$str = substr($str, $words, $strlen);
}
return $result;
}
/* Example */
$res = str_split_len("Split me !haha!", 3);
print_r($res);
?>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: trying to access array offset on value of type bool
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.