Grow your CSS skills. Land your dream job.

[Solved] Preg_replace Multiple Matches

  • # September 22, 2009 at 10:25 am

    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?

    # September 22, 2009 at 12:13 pm

    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.

    # September 22, 2009 at 6:48 pm
    "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.

    # September 23, 2009 at 8:31 am

    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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".