ARTICLE AD BOX
I have some text like this:
Lorem ipsum THIS dolor sit THIS amet, consectetur THIS adipiscing elit.and it needs to be like this:
Lorem ipsum THIS1 dolor sit THIS2 amet, consectetur THIS3 adipiscing elit.Notice the addition of the number after each instance of "THIS". The number must increase by 1 each time "THIS" is found.
How can I accomplish this?
63.1k18 gold badges97 silver badges104 bronze badges
1
preg_replace_callback lets you use a function to return a new value for each string replacement made.
<?php $text = 'Lorem ipsum THIS dolor sit THIS amet, consectetur THIS adipiscing elit.'; $counter = 0; $result = preg_replace_callback('/THIS/', function($matches) use (&$counter) { $counter++; return 'THIS' . $counter; }, $text); echo $result;172k17 gold badges151 silver badges232 bronze badges
i don't know why you need this but here is a solution
<?php $var="THIS"; $string=" Lorem ipsum THIS dolor sit THIS amet, consectetur THIS adipiscing elit. " $array=explode($var,$string); for($i=0;$i<count($array)-1;$i++){ $array[$i]=$array[$i]." THIS".$i+1; }; $string=implode("",$array); echo $string; ?>Explore related questions
See similar questions with these tags.
