it might be very easy but i could not do it..
given a string:
$str="i have an apple[1], and another one [2], and another[3]";
i want to replace [1], [2] .. with <tag id=1> <tag id=2>
i tried $str2 = preg_replace('/[([1-9][0-9]*)]/', '<tag id=1>', $str);
but can not insert a variable to do
$str2 = preg_replace('/[([1-9][0-9]*)]/', '<tag id=$var>', $str);
the regex i am using is also a problem, it works for some cases but does not for some 🙁
any help is deeply appreciated..
EDIT:
as @m42 and @scibuff pointed out, valid regex would be: /\[([1-9][0-9]*)\]/
but how to increment for each replacement?
EDIT 2:
i misunderstood M42’s answer, thanks.
But what if i have another string;
str2="i have an egg [4], and another egg [5]";
how can i continue the increment started by first preg_replace?
i mean, desired result is:
i have an apple <tag id=1>,... i have an egg [4]..
EDIT 3: SOLVED by M42
-in fact second part of the question is meaningless, preg_replace will increment continously.. thanks all!!
How about:
Here is a test:
output: