This is a problem related to adding a counter when renaming a value with the same name.
I have a form with a textarea where you can write text inside. Inside the textarea, the writer can write the word foto which must follow a particular path when sending the form. I specify that the written text will end up in a txt file.
I created a code that replaces the word *foto*
with "<img src="img/foto$y.jpg">
assuming that each word *foto*
is replaced in "<img src="img/foto1. jpg">, "<img src="img/foto2.jpg">
in the txt file after submitting the form…
Instead I find that the file is generated with n.2 "<img src="img/foto1.jpg">
without increasing the counter (1-2-3 etc… based on the number of photos).
In the code $vfoto
is the number of photos the user has decided to upload. $v5
is the article.
Html:
<form>
<textarea name="post_content" id="article"</textarea>
</form>
Text write Textarea box:
<p>Test</p>
<p>*foto*</p>
<p>*foto*</p>
PHP:
$v5 = $_POST["post_content"];
if ($vfoto > 0){
$y = 1;
for ($x = 1; $x <= $vfoto; $x++) {
$v5 = str_ireplace("<p>*foto*</p>","<img src="img/foto$y.jpg"
class="img_article_box">",$v5);
$y++;
}
$myfile = fopen("provafile.txt","w") or die("Unable to open file!");
fwrite($myfile, html_entity_decode($v5));
fclose($myfile);
}
The result I would expect is:
<p>test</p>
<img src="img/foto1.jpg" class="img_article_box">
<img src="img/foto2.jpg" class="img_article_box">
2
Answers
simple do this, use regex and the prebuild php function to handle replacements,
Input
Output
You can use the
preg_replace
function with the limit argument (fourth parameter) to replace just one instance of the text. This would allow you to replace the next instance in the text.