What would be the best way to implement the following line in the middle of the text? I want readers to see a google ad right in the middle of the article. I’ve seen this type of thing on many pages, but not sure of the best way to tackle it.
Edit: Actually that can be simplified, as array_splice actually removes the first instances from the original array …
$test = "Sentence 1. Sentence 2. Sentence 3. Sentence 4.";
$sentences = explode(". ", $test);
$banner = "I'm only here for the beer. ";
$first = array_splice($sentences,0 ,2);
// var_dump($sentences); // now only contains remaining elements
$output = join(". ",$first) . '. ' . $banner ;
$output .= join(". ", $sentences);
echo $output;
You will run into trouble with this if your text from the db contains other instances of ". " (dot space), or more importantly if your text contains html markup.
You may find you are splitting on sentences within tags, such as:
Cups, thanks for your help. I took what you suggested, made some minor changes and tried to learn something from this. For some reason, however, I’m getting two periods after the end of each sentence. Here is my code:
$testimonialText = nl2br($testimonialText); // This will insert <br /> tags into the string
// Split on whitespace between sentences preceded by a punctuation mark
$sentences = preg_split(‘/(?<=[.?!;:])\s+/’, $testimonialText, -1, PREG_SPLIT_NO_EMPTY);
Maybe this would work better if instead of counting the number of sentences, it counts the number of paragraphs? Once the number of paragraphs are known, we could divide that number by two and then insert the Google ads right in the middle. Thoughts? Here are the results if you want to see them:
Split on paragraphs if that makes more sense to you.
You have to be very clear in your mind that you have catered for every single possibility of what constitutes a “paragraph” when the output is coming from a textarea (or worse, a wysiwyg-enabled textarea).
Set up some test cases in an array and keep working on the solution till you have what you want and it works 100%.
$tests = array(
"<p>Para 1</p><p>Para 2</p>" // what you might expect
, "<p>Para 1<br /><br /><br />Para 2</p>" // should this replace 2 <br />s with a <p>?
, "Para1<br /><br /></p>" // how should this be handled?
);
// add more esoteric examples if you want your function to be bombproof
array_map($test, "MySplittingFunction");