Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End [Solved] Preg_replace Multiple Matches

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #26208
    gilbitron
    Member

    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:

    Code:
    $html = file_get_contents($file);
    $fh = fopen($file, ‘w’) or die(“Failed to write file “. $file);
    $newHTML = preg_replace(‘/(?s)

    (.*?)

    /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?

    #64566
    Argeaux
    Participant

    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.

    #64589
    gilbitron
    Member
    "Argeaux" wrote:
    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.

    #64603
    gilbitron
    Member

    Managed to get it sorted. Ended up using preg_match_all and str_replace to get it done:

    Code:
    $html = file_get_contents($file);
    $fh = fopen($file, ‘w’) or die(“Failed to write file “. $file);
    preg_match_all(‘/(?s)

    (.*?)

    /mi’, $html, $matches, PREG_SET_ORDER);
    $i = 0;
    foreach($matches as $val) {
    $html = str_replace($val[0], ‘

    ‘. $data[$i] .’

    ‘, $html);
    $i++;
    }
    fwrite($fh, $html);
    fclose($fh);

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘Back End’ is closed to new topics and replies.