Question

I want to explode a string by (for example) 50 symbols (min), but without dividing words in 2 parts.

Is this possible?

Using str_split() will cause the last word to get split, which is what I don't want.

Example: splitting string by 5 symbols;

$input = 'This is example, example can be anything.';

$output[0] = 'This';
$output[1] = 'is example,';
$output[2] = 'example';
$output[3] = 'can';
$output[4] = 'be anything';
Was it helpful?

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:

Codepad Example Here

$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."
// }

OTHER TIPS

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 :-)

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);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top