Jump to content

splitting a string and adding something


anthropos9

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.
Link to comment
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.
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.