Jump to content

Archived

This topic is now archived and is closed to further replies.

anthropos9

splitting a string and adding something

Recommended Posts

I'm working on a news site where I need to add an advertisement about 200 words into the article and then have the text wrap around it.  I'm going to enclose the ad in a <div> tag that is going to be floated to the left.  To do this I need to split the article in two at the 200 word point, add the <div> code and then continue the article.  Can anyone help me on how to do this.  I've seen that there are a lot of different ways to split a string, I'm just not sure which one is the best for this implementation.  Thanks.

Share this post


Link to post
Share on other sites
say hello to explode()

[code]
$part1="";
$text="all the words";
$text2=explode(" ", $text);

for($i=0; $i<200; $i++)        //to get the first 200 words
{
      $part1.=$text2[$i]. " ";  //adds the next word to part 1 with a space after each word.
}
$num=count($text2);
for($i=200; $i<=$num; $i++)
{
      $part2.=$text2[$i]. " ";
}

[/code]

that will leave part1 with the first 200 words, and part2 with whatever else was left.  At least I think, and hope.

Share this post


Link to post
Share on other sites
I'd take it a step further and instead of using the for loop, use array_slice and implode--this should help speed it up a bit:

[code]
$text="all the words";
$text2=explode(" ", $text);

//get the first 200 words
$front = array_slice($text2, 0, 199);
$part1 = implode(" ", $front);

//get the remainder
$back = array_slice($text2, 200);
$part2 = implode(" ", $back);

[/code]

Of course this doesn't deal with cases where there is LESS than 200 words.  Also, it could split strings that you would NOT want spit for example a name.  What happens if "word" number 200 is Bill and "word" number 201 is Smith?  Is that going to be a problem?


Hope this helps.

Share this post


Link to post
Share on other sites
Thanks for your help.  I will try this in the morning.  The separating of two words that belong together -- like bill smith -- shouldn't be a problem.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.