/    Sign up×
Community /Pin to ProfileBookmark

Split a string after the 5th {space}

I was wondering how I would go about splitting a string after a certain number of whatever…. Example. I want to split a string after the 50th {space}…

such as… This is a paragraph that should be split into two pieces.

How do I have that paragraph split after the word that which is the 5th space?

to post a comment
PHP

19 Comments(s)

Copy linkTweet thisAlerts:
@NogDogJun 29.2006 — What do you mean by "split"?

Pending a clarification, perhaps the wordwrap() function is what you need?
[code=php]
echo wordwrap($string, 20, "<br>n");
[/code]
Copy linkTweet thisAlerts:
@firmanauthorJun 29.2006 — By SPLIT I mean I want to end the sentence short. Basicaly what I want is after the 5th word of any setence I want it to stop and store word 1-5 in a variable.
Copy linkTweet thisAlerts:
@The_Little_GuyJun 29.2006 — He wants the sentence:

[B]This is a paragraph that should be split into two pieces.[/B]

To end up like this:

[B]This is a paragraph that[/B]

From what I was reading
Copy linkTweet thisAlerts:
@firmanauthorJun 29.2006 — Exactly.
Copy linkTweet thisAlerts:
@bokehJun 29.2006 — Can you post the text as a block so I can see how it is formated?

Also do you want to retain the second section or dump it.
Copy linkTweet thisAlerts:
@firmanauthorJun 29.2006 — The Philadelphia Wings finished the 2006 regular season with an 8-8 record, but missed the playoffs on a three-way tiebreaker. The Wings continue to build, and return an impressive lineup for 2007. Jake Bergey, Sean Greenhalgh and Jeff Ratcliffe are back on offense, while Tom Hajek, Peter Jacobs and Rob Van Beek are the top protected players on defense, with Matt Roik in goal.


That is the text.... I just want to take a section of that.... Can you show me how to keep the other half...as well as just dump the other half?
Copy linkTweet thisAlerts:
@SheldonJun 29.2006 — this is proberly a long way of doing it but it works

[code=php]
<?php
$str = "The Philadelphia Wings finished the 2006 regular season with an 8-8 record, but missed the playoffs on a three-way tiebreaker. The Wings continue to build, and return an impressive lineup for 2007. Jake Bergey, Sean Greenhalgh and Jeff Ratcliffe are back on offense, while Tom Hajek, Peter Jacobs and Rob Van Beek are the top protected players on defense, with Matt Roik in goal.";

$five = explode(' ', $str);
$text = $five[0] ." ". $five[1] ." ". $five[2] ." ". $five[3] ." ". $five[4];
echo($text);

?>[/code]
Copy linkTweet thisAlerts:
@firmanauthorJun 29.2006 — This would work, but there HAS to be a better way.
Copy linkTweet thisAlerts:
@bokehJun 30.2006 — [code=php]<?php

$text = 'The Philadelphia Wings finished the 2006 regular season with an 8-8 record, but missed the playoffs on a three-way tiebreaker. The Wings continue to build, and return an impressive lineup for 2007. Jake Bergey, Sean Greenhalgh and Jeff Ratcliffe are back on offense, while Tom Hajek, Peter Jacobs and Rob Van Beek are the top protected players on defense, with Matt Roik in goal.';

# number of words to capture
$capture = 5;


if(preg_match_all('/[A-Z][^.]+[.]/', $text, $matches))
{
foreach($matches[0] as $k => $match)
{
$first_five = implode(' ', array_slice($words = explode(' ', $match), 0, $capture));
$remainder = implode(' ', array_slice($words, $capture));
$sentences[] = array('first_five' => $first_five, 'remainder' => $remainder);
}

# test it
header('Content-Type: text/plain');
print_r($sentences);
}
else
{
echo 'No sentences found';

/* output produced

Array
(
[0] => Array
(
[first_five] => The Philadelphia Wings finished the
[remainder] => 2006 regular season with an 8-8 record, but missed the playoffs on a three-way tiebreaker.
)

[1] => Array
(
[first_five] => The Wings continue to build,
[remainder] => and return an impressive lineup for 2007.
)

[2] => Array
(
[first_five] => Jake Bergey, Sean Greenhalgh and
[remainder] => Jeff Ratcliffe are back on offense, while Tom Hajek, Peter Jacobs and Rob Van Beek are the top protected players on defense, with Matt Roik in goal.
)

)

*/

?>[/code]
Copy linkTweet thisAlerts:
@SheldonJun 30.2006 — The above solution (using preg_match) would be better. This is another solution.

[code=php]<?php

$paragraph = "The Philadelphia Wings finished the 2006 regular season with an 8-8 record, but missed the playoffs on a three-way tiebreaker. The Wings continue to build, and return an impressive lineup for 2007. Jake Bergey, Sean Greenhalgh and Jeff Ratcliffe are back on offense, while Tom Hajek, Peter Jacobs and Rob Van Beek are the top protected players on defense, with Matt Roik in goal.";

$sentences = explode(". ", $paragraph);

foreach($sentences as $value) {

//Display Sentences
echo ("$value<br />");

//Get the words or each sentence
$words_per_sentence = explode(" ", $value);

foreach($words_per_sentence as $key => $word) {
echo ("Word $key is $word<br />");

//Grab first five
if ($key <= 4) {
$first_five .= "$word ";
}

}

//Display first five of each sentence
echo ("$first_five<br />");

//Reset first five for next sentence
$first_five = "";

}

?>[/code]


To get the remaining try something like:
[code=php]

//Grab first five
if ($key <= 4) {
$first_five .= "$word ";
} else {
//Else grab remaining
$remaining .= "$word ";
}

[/code]


You will also need to clear the var after each sentence.
Copy linkTweet thisAlerts:
@NogDogJun 30.2006 — [code=php]
/*
array first_words(str text, int numWords)
returns array: element 0 is first numWords of text, element 1 is rest of text
*/
function first_words($text, $numWords)
{
if(preg_match_all('/^((S+s+){1,'.$numWords.'})(.*)$/', $text, $matches) !== FALSE)
{
$output[0] = $matches[1][0];
$output[1] = $matches[3][0];
return($output);
}
else
{
return(FALSE);
}
}
// SAMPLE USAGE:
$test = <<<EOD
This is a test. It is only a test. The end.
EOD;
list($start, $end) = first_words($test, 5);
echo "START: $start'<br>";
echo "END: '$end'";
[/code]
Copy linkTweet thisAlerts:
@bokehJun 30.2006 — Looking at Nogdog's answer makes me think that maybe I didn't understand the question. My solution gave the first 5 words of each sentence but to grab the first few words from the global block of text you could do it like this:[code=php]<?php

$text = 'The Philadelphia Wings finished the 2006 regular season with an 8-8 record, but missed the playoffs on a three-way tiebreaker. The Wings continue to build, and return an impressive lineup for 2007. Jake Bergey, Sean Greenhalgh and Jeff Ratcliffe are back on offense, while Tom Hajek, Peter Jacobs and Rob Van Beek are the top protected players on defense, with Matt Roik in goal.';

$capture = 5;

echo 'START: '.implode(' ', array_slice($words = explode(' ', $text), 0, $capture))."<br>n";
echo 'END: '.implode(' ', array_slice($words, $capture));

?>[/code]
Copy linkTweet thisAlerts:
@NogDogJun 30.2006 — I like Bokeh's solution, but if your word boundaries could possibly be characters other than spaces (tabs, newlines, etc.) then you might want to use the preg_split() function instead of explode(), splitting on a [b]'/s+/'[/b] pattern. Should it be necessary to maintain newlines and such in the new strings, then you might have to use something like my proposed solution.
Copy linkTweet thisAlerts:
@bokehJun 30.2006 — Should it be necessary to maintain newlines and such in the new strings, then you might have to use something like my proposed solution.[/QUOTE]You could use a zero width positive lookaround to do that and then [I]implode()[/I] without any [I]glue[/I]! [B][CODE]/(?<=s(?=w))/[/CODE][/B][code=php]$first_five_words = implode(array_slice(preg_split('/(?<=s(?=w))/', $text), 0, 5));[/code]
Copy linkTweet thisAlerts:
@firmanauthorJul 02.2006 — Anyone else have more ways to do this? I really thought there would be a single line piece of code to do something like this.
Copy linkTweet thisAlerts:
@SheldonJul 02.2006 — Talk about ungreatfull, You have had both Bokeh and NogDog answer this for you, Two of the best PHP developers on these forums and still no Thanks but "huh can't you do better?"
Copy linkTweet thisAlerts:
@oldmanJul 03.2006 — Here is one more way, just for the heck of it.

[code=php]$text="The Philadelphia Wings finished the 2006 regular season with an 8-8 record, but missed the yada yada yada...";

preg_match("/(w*s){5}/",$text,$match);
echo"$match[0]";[/code]


The text must be at least five words long to be recognized.
Copy linkTweet thisAlerts:
@log2Jul 03.2006 — I believe that this would be the best and easiest way to split after the 5th space:[code=php]<?
$string = explode(" ", $string, 5);
$string = implode(' ', $string);
echo $string;
?>[/code]
Copy linkTweet thisAlerts:
@bokehJul 03.2006 — best and easiest[/QUOTE] :rolleyes: If you had bothered to test the "best and easiest" way you would find it outputs the original string without any modification whatsoever. It is also subject to the other problems of exploding on a space mentioned further up the thread.
×

Success!

Help @firman 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.15,
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,
)...