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?

ADyson's user avatar

ADyson

63.1k18 gold badges97 silver badges104 bronze badges

Peter Struyk's user avatar

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;

AKX's user avatar

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; ?>

Reda ait's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.