Question

I have a problem on my script it duplicates the output from the .html file. here is my code below.

php:

<?php
$html = file_exists('try.html') ? file_get_contents('try.html') : die('unable to open the file');

$data['test1'] = 'WRITE 1';

$data['test2'] = 'WRITE 2';

foreach ($data as $search => $value)
{
    if(preg_match_all('#(<([a-zA-Z]+)[^>]*id=")(.*'.$search.')("[^>]*>)([^<]*?)(</\\2>)#ism', $html, $matches, PREG_SET_ORDER))
    {
        foreach($matches as $match) 
        {
            $xhtml = str_replace($match[5],$value,$html);
            echo $xhtml;
        }
    }
}
?>

html:

<html>
<head>
<title>TRY</title>
</head>
<body>
<div id="test1">A</div>
<div id="test2">B</div>
</body>
</html>

OUTPUT:

WRITE 1
B

A
WRITE 2

it duplicates the output.

DESIRED OUTPUT:

WRITE 1
WRITE 2
Was it helpful?

Solution

You have this as your foreach loop:

foreach($matches as $match) 
{
    $xhtml = str_replace($match[5],$value,$html);
    echo $xhtml;
}

The echo is inside the loop, so you do one replacement each time, then echo $xhtml each time. What you want is this:

<?php
$html = file_exists('try.html') ? file_get_contents('try.html') : die('unable to open the file');

$data['test1'] = 'WRITE 1';

$data['test2'] = 'WRITE 2';

foreach ($data as $search => $value)
{
    if(preg_match_all('#(<([a-zA-Z]+)[^>]*id=")(.*'.$search.')("[^>]*>)([^<]*?)(</\\2>)#ism', $html, $matches, PREG_SET_ORDER))
    {
        foreach($matches as $match) 
        {
            $html = str_replace($match[5],$value,$html);
        }
    }
}
echo $html;
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top