/    Sign up×
Community /Pin to ProfileBookmark

Splitting a string into equal parts

Hello,

I’m wanting to split a variable length string which will just be plain text into three strings, so for instance

[CODE]$string = “hello world how are you today”;

$string1 = “hello world”;
$string2 = “how are”;
$string3 = “you today”;[/CODE]

I looked at explode, but without somekind of marker to use as the split point i don’t think i can use that?

Ideally i would like to count the words, then split them equally in the spaces, as to not slice words in half etc, but i’m not sure how to acheive this? The text won’t be massive, a couple of hundred characters at the most.

Thanks

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@thraddashJan 05.2011 — This was a little interesting...

[code=php]$string = 'hello world how are you today';

$data = explode(' ', $string);
$part = ceil(count($data) / 3);

$string1 = implode(' ', array_slice($data, 0, $part));
$string2 = implode(' ', array_slice($data, $part, $part));
$string3 = implode(' ', array_slice($data, $part * 2));

echo $string1 . '<br />';
echo $string2 . '<br />';
echo $string3 . '<br />';[/code]
Copy linkTweet thisAlerts:
@NogDogJan 06.2011 — You could use the wordwrap() function if you want to do it by character count instead of word count, e.g.:
[code=php]
<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.";

$columns = wordwrap($text, ceil(strlen($text)/3), "</td>n<td>");
echo "<table><tr><td>" . $columns . "</td></tr></table>";
[/code]
×

Success!

Help @copes spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...