treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Preg_replace Multiple Matches

  • Hi guys.

    Here is one that has stumped me today. I'm taking the HTML of a file and replacing any div's with the class "ecms" with the content in an array "data" then saving the file. Just now I have:


    $html = file_get_contents($file);
    $fh = fopen($file, 'w') or die(\"Failed to write file \". $file);
    $newHTML = preg_replace('/(?s)<div class=\"ecms\">(.*?)<\/div>/mi', $data[0], $html);
    fwrite($fh, $newHTML);
    fclose($fh);


    This works but it replaces all of the matches with only the first item in the "data" array. What I would like to do is replace each match with the subsequent item in the "data" array (don't worry about the matches and the array count being the same). Does anyone know how to do this?
  • i didnt test it, but a quick look at the php websites gives me this:

    http://nl.php.net/preg_match_all

    maybe you could try that.
  • "Argeaux" said:
    i didnt test it, but a quick look at the php websites gives me this:

    http://nl.php.net/preg_match_all

    maybe you could try that.


    I did look at preg_match_all but I don't really know how to use it, and even if I did it doesn't do the replace functionality that I need.
  • Managed to get it sorted. Ended up using preg_match_all and str_replace to get it done:


    $html = file_get_contents($file);
    $fh = fopen($file, 'w') or die(\"Failed to write file \". $file);
    preg_match_all('/(?s)<div class=\"ecms\">(.*?)<\/div>/mi', $html, $matches, PREG_SET_ORDER);
    $i = 0;
    foreach($matches as $val) {
    $html = str_replace($val[0], '<div class=\"ecms\">'. $data[$i] .'</div>', $html);
    $i++;
    }
    fwrite($fh, $html);
    fclose($fh);