/    Sign up×
Community /Pin to ProfileBookmark

make a newline every 5th word in a string

I have a string with 10 words in it. I want to make a newline every 5th word. I have tried with

[code]$string = “Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10″;

while(count(explode(” “,$string, 5)) == 5)
{
echo “$string<br />”;
$string = strtok(” n”);
}[/code]

But it just prints out the ten words in a line.
Pls help!

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@apeaceJan 28.2008 — This code will make a newline after every fifth word of any string (where a word is text with one space on the left and one space on the right):

[code=php]function newlineEveryFive($str){
$array = explode(" ", $str);
for($i=0;$i<count($array);$i++){
if($i!=0 && $i%5==0)
$out .= "n".$array[$i]." ";
else
$out .= $array[$i]." ";
}
return $out;
}[/code]


If you want it to insert <br /> instead of n, just make a replacement in the code.

Does this help?
Copy linkTweet thisAlerts:
@NogDogJan 28.2008 — Depending on what exactly you want to accomplish, you might want to look at the [url=http://www.php.net/wordwrap]wordwrap() function[/url]. This wraps based on character count instead of word count, but that might end up giving you more even breaks.
Copy linkTweet thisAlerts:
@RoxxorauthorJan 28.2008 — This code will make a newline after every fifth word of any string (where a word is text with one space on the left and one space on the right):

[code=php]function newlineEveryFive($str){
$array = explode(" ", $str);
for($i=0;$i<count($array);$i++){
if($i!=0 && $i%5==0)
$out .= "n".$array[$i]." ";
else
$out .= $array[$i]." ";
}
return $out;
}[/code]


If you want it to insert <br /> instead of n, just make a replacement in the code.

Does this help?[/QUOTE]


I don´t know how to thank you, but thanks! That really helped me. ?

Actually I already got a function that made a new line every 5 word but it didn´t work together with the FPDF thing I was woking on. So you really helped me.
Copy linkTweet thisAlerts:
@apeaceJan 29.2008 — Cool man. Glad to help. I think I'm gonna stick around this forum, so keep posting questions!
×

Success!

Help @Roxxor 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 5.19,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...