Using substr_replace inside a nested loop almost works but duplicates the haystack what am I missing?

I’m an amateur web programmer. From time to time I like to build something for personal use, taking a lot of pleasure from the result when a script finally does what I want it to do. So I learn as I go, but now I’m stuck and I hope someone here would be willing to take a look at what I’m doing.

I’m working on a project that takes text files from a folder and searches the text of each file for specific keywords that correspond to image files that I’m trying to insert in the text as an html image tag using php. I got it almost working: the correct images get inserted at the desired points, and text files that do not contain a keyword remain untouched, but the text files that have images inserted are doubled: one text file with added image and one original text file. I have tried different approaches but either it doesn’t work at all, or the text files with inserted images are duplicated.

Where lies the foult? Am I going at it the wrong way?

Here is my code:

<?php
$path = // array of .txt-filenames with plain tekst
$imagepath = // array of .jpg-filenames

foreach ($path as $file) {

$haystack = file_get_contents("$file");

    foreach ($imagepath as $imagefile) {
        $needle = $imagefile;
        $position = strpos($haystack,$needle);

        if ($position !== false) {$output = substr_replace($haystack, "<img src='$imagefile'>", $position, 0);} else {$output = $haystack;}
              
        echo $output; }

}
?>