Search code examples
phpfile-get-contentskey-valuearray-key

PHP: php and .html file separation


I'm currently working on separating HTML & PHP code here's my code which is currently working for me.

code.php

<?php
$data['#text#'] = 'A';

$html = file_get_contents('test.html');

echo $html = str_replace(array_keys($data),array_values($data),$html);
?>

test.html

<html>
<head>
<title>TEST HTML</title>
</head>
<body>
<h1>#text#</h1>
</body>
</html>

OUTPUT: A

it search and change the #text# value to array_value A it works for me.

Now i'm working on a code to search "id" tags on html file. If it's searches the "id" in ".html" file it will put the array_values in the middle of >

EX: <div id="test"> **aray_values here** </div>

test.php

<?php

$data['id="test"'] = 'A';

$html = file_get_contents('test.html');

foreach ($data as $search => $value)
{
    if (strpos($html , $search))
    {
        echo 'FOUND';
        echo $value;
    }
}

?>

test.html

<html>
<head>
<title>TEST</title>
</head>
<body>
<div id="test" ></div>
</body>
</html>

My problem is I don't know how to put the array_values in the middle of every ></ search in the .html file.

Desired OUTPUT: <div id="test" >A</div>


Solution

  • function callbackInsert($matches)
    {
        global $data;
        return $matches[1].$matches[3].$matches[4].$data[$matches[3]].$matches[6];
    }
    
    
    $data['test'] = 'A';
    
    $html = file_get_contents('test.html');
    
    foreach ($data as $search => $value)
    {
        preg_replace_callback('#(<([a-zA-Z]+)[^>]*id=")(.*?)("[^>]*>)([^<]*?)(</\\2>)#ism', 'callbackInsert', $html);
    }
    

    Warning: code is not tested and could be improved - re global keyword and what items are allowed between > and

    Regular expression explanation:

    (<([a-zA-Z]+) - any html tag starting including the last letter of the tag
    [^>]* - anything that is inside a tag <>
    id=")(.*?)(" - the id attribute and its value
    [^>]* - anything that is inside a tag <>
    >) - the closing tag
    ([^<]*?) - anything that is not a tag, tested by opening a tag <
    (</\\2>) - the closing tag matching the 2nd bracket, ie. the matching opening tag