There are two main problems with your code that are both causing the unexpected result you're achieving.
First, you are not understanding the scope of PHP variables properly.
Secondly, you are not looping through the divs withing your string, you're just telling PHP to go through the string one time and replace all of the instances of "div" with an identified div. Therefore, the function is only called once, because the str_replace function is only called once.
A standard variable within a function will stay within that function, and will never have any bearing on variables outside of that function.
That said, I will get a little more specific by adding some comments to your code:
PHP Code:
$i=0; # Here, you set the global variable $i to 0
function divCount(){ # Here, you begin your function definition
$i = $i + 1; # Here, you increase the value of a brand-new variable called $i within your function. PHP interprets the value of the undeclared variable as 0. You could really do this step as $i++; instead of $i = $i + 1; to make things a little simpler
$iString = $i + ""; # This step is unnecessary, as, PHP will interpret the integer as a string when you append it to your return statement anyway
return "div".$iString; # Because I am recommending that you remove the statement above, this should become "div".$i
} # Here you close your function definition
$strResult = str_replace("<DIV STYLE=", "<DIV ID='".divCount()."' STYLE=", $result); # Here you are attempting to replace all instances of "<DIV..." with "<DIV ID...", with the ID being incremented by your function. However, as described above, you're really only running the "divCount" function once.
echo $strResult;
In order for the function to operate the way you intend, you will need to add $i as a parameter in your function, and include it byRef instead of the standard byVal. To include a variable byRef, you need to precede the variable name with an ampersand (&) when declaring it inside your function opening. For example:
PHP Code:
function divCount($i) { # This opening will simply accept the value of $i, but any changes made to that variable within the function will be thrown away when the function is finished
function divCount(&$i) { # This opening will accept the actual variable $i, and any changes made to that variable within the function will stay that way even after the function is finished.
Now, onto problem number two, which is slightly more complicated. You really need to loop through each occurrence of divs within your string. Otherwise, as mentioned above, you're only invoking the divCount function once.
I can't really come up with a reliable way to do that at the moment, but if you don't come up with anything, let me know and I'll try to think about it. Good luck.