开发者

Cut string into pieces without breaking words.

开发者 https://www.devze.com 2023-03-28 04:31 出处:网络
I have a string: $str = \'Hello World, Welcome World, Bye World\'; I want to cut above stri开发者_JS百科ng into pieces. Each piece should be of 10 characters. If a word is going to be cut, then mov

I have a string:

$str = 'Hello World, Welcome World, Bye World';

I want to cut above stri开发者_JS百科ng into pieces. Each piece should be of 10 characters. If a word is going to be cut, then move that word to next line.

For Example:

$output = array();

$output[0] = 'Hello ';
$output[1] = 'World, ';
$output[2] = 'Welcome ';
$output[3] = 'World, Bye'; 
$output[4] = 'World';

Is there a shortest way without so many if else and loops.

Thanks


Use wordwrap. By default it wraps whole words and does not cut them into pieces.

echo wordwrap('Hello World, Welcome World, Bye World', 10);

If you want an array, explode afterwards:

print_r(explode("\n", wordwrap('Hello World, Welcome World, Bye World', 10)));


string test = 'Hello World, Welcome World, Bye World';
string[] splited = test.Split(' ');
foreach (string str in s.Split(splited))
{
Console.WriteLine(str);
}

Note: Its written in C#, I hope it will give you an Idea.

Regards


Although not exactly the answer, some similar problem is like this:

You have a long string, you want to break that string into chunks. You prefer not to break words, but words can be broken if word is very long.

$string = "Hello I am a sentence but I have verylongwordthat I can split";

You will split the words in this sentence if word is very long, like this:

$pieces = explode(" ",$string);
$textArray=array();
foreach ($pieces as $p) {
    $textArray= array_merge($textArray, str_split($p, 10));
}
$stringNew=implode(" ",$textArray);

output:

"Hello I am a sentence but I have verylongwo rdthat I can split"
0

精彩评论

暂无评论...
验证码 换一张
取 消