how to use the replace function to replace consecutive DIVs with IDs

Discussion in 'PHP' started by gilgalbiblewheel, Apr 2, 2008.

  1. #1
    I'm trying to understand where I went wrong I need to insert by replacing <DIV with <DIV ID="div0", <DIV ID="div1", <DIV ID="div2", <DIV ID="div3",...
    $i=0;
    function divCount(){
    $i = $i + 1;
    $iString = $i + "";
    return "div".$iString;
    }
    $strResult = str_replace("<DIV STYLE=", "<DIV ID='".divCount()."' STYLE=", $result);
    echo $strResult;
    PHP:
    This is what's happening so far:
    <DIV ID='div1' STYLE="POSITION:ABSOLUTE;TOP:69;LEFT:177" CLASS="APFont00000">...</DIV>
    <DIV ID='div1' STYLE="POSITION:ABSOLUTE;TOP:88;LEFT:290" CLASS="APFont00001">...</DIV>
    <DIV ID='div1' STYLE="POSITION:ABSOLUTE;TOP:103;LEFT:231" CLASS="APFont00001">...</DIV>
    <DIV ID='div1' STYLE="POSITION:ABSOLUTE;TOP:154;LEFT:71" CLASS="APFont00002">...</DIV>
    Code (markup):

     
    gilgalbiblewheel, Apr 2, 2008 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    You need to loop through the html so that each div gets it's own id.

    There may be a better way to do this, but this seemed reasonable off the top of my head.

    
    
    $i=0;
    $finalString = '';
    
    $newString = explode("\n",$html_file);
    
    foreach($newString as $line)
    {
    
    if(strpos($line,'<DIV STYLE=') !== false)
    {
    
    $line = str_replace("<DIV STYLE=", "<DIV ID='div".$i."' STYLE=", $line);
    $i++;
    }
    
    $finalString .= $line."\n";
    
    }
    
    
    PHP:
     
    jestep, Apr 2, 2008 IP
  3. gilgalbiblewheel

    gilgalbiblewheel Well-Known Member

    Messages:
    435
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #3
    Then you have to echo it right? But the source shows blank.
    $i=1;
    $finalString = '';
    $newString = explode("\n",$html_file);
    foreach($newString as $result)
    {
    if(strpos($result,'<DIV STYLE=') !== false)
    {
    $result = str_replace("<DIV STYLE=", "<DIV ID='".$i."' STYLE=", $result);
    $i++;
    }
    $finalString .= $result."\n";
    }
    echo $finalString;
    PHP:
     
    gilgalbiblewheel, Apr 2, 2008 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    Try changing $html_file back to $result. I changed the name by accident.

    
    
    $newString = explode("\n",$result);
    
    
    PHP:
     
    jestep, Apr 2, 2008 IP
  5. gilgalbiblewheel

    gilgalbiblewheel Well-Known Member

    Messages:
    435
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #5
    wow you did it! Thanks!
     
    gilgalbiblewheel, Apr 2, 2008 IP