I am trying to split html body in half and insert ad banner between. I originally tried with
$position = split_pos($body);
$d_content1 = substr($body,0,$position);
$d_content2 = substr($body,$position+1);
echo $d_content1;
/********insert ad code goes here*****/
echo $d_content2;
/********function split_pos***********/
function split_pos($text) {
/* find middle space in text **/
$mid = (int) strlen($text)/2 - 1;
$cut = strpos($text , ' ' , $mid);
$part1= substr($text , 0 , $cut + 1);
$pos1 = strrpos($part1 , '<');
$pos2 = strrpos($part1 , '>');
if (($pos1 < $pos2) or ($pos1 === False))
return $cut; /* no html tag around */
$pos3 = strpos($text , '>' , $cut1 + 1);
if($pos3 !== False)
return $pos3; /* end of middle html tag */
else return $cut; /* unbalancing < > */
}
But this code can cut between HTML <a></a> Tag off which make html a link doesn't work anymore.
So I tried code below:
//put article into arrays seprated by html tags
$result = preg_split('~(</?[^>]+>)~', $body, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$max = sizeof($result);
// return middle array key for the article
$position = split_body($result, $max);
// print first half of array
$s = '';
for ($x=0; $x <= $position; $x++){
$s .= $result[$x];
}
echo $s;
/********* insert ad banner code here********/
// print 2nd half of article
$z = '';
for ($y=$position+1; $y<=$max; $y++){
$z .= $result[$y];}
echo $z;
/***split body function code **/
/**** I tried passing reference to improve performace****/
function split_body(&$array_result, &$array_size){
// find the middle section of article
$mid_key = intval($array_size/2);
$mid_found = false; // found it or not
while (!$mid_found) { //check if middle section found
// check if the line code have <div> or <p> tag. separate
If (preg_match("/<(div|p)/i", $array_result[$mid_key])){
$mid_key -=1;
$mid_found = true;
} elseif (preg_match("/<\/(div|p)/i", $array_result[$mid_key])){
$mid_found = true;
}
else{
$mid_key++;
if ($mid_key == $array_size){
$mid_found = true;
}
}
}
return $mid_key;
}
The code above works. It separates the body by html tags and put them into array.
But it causes my server load to go up like 300% or 400%. eventually it will overload the server.
Can anybody explain why it overloaded my server? ( I am thinking the preg_split made too big of array, but I am not sure) or have better solution to this problem? (Split html body in half without breaking <a></a> tags).
Thank you very much.