I have one sentence like this:
{pattern} test {pattern} how r u {pattern}
How can I replace {pattern}
with different values like
{AAA} test {BBB} how r u {CCC}
I have one sentence like this:
{pattern} test {pattern} how r u {pattern}
How can I replace {pattern}
with different values like
{AAA} test {BBB} how r u {CCC}
If you wish to replace the same pattern with something else every time you could consider using preg_replace_callback()
. At every match, a function is executed and you can return a different string at every invocation:
$s = '{pattern} test {pattern} how r u {pattern}';
// this gets called at every match
function replace_pattern($match)
{
// list of replacement strings $a and a looping counter $i
static $a = array('AAA', 'BBB', 'CCC');
static $i = 0;
// return current replacement string and increase counter
return $a[$i++ % count($a)];
}
echo preg_replace_callback('/{pattern}/', 'replace_pattern', $s);
This solution cycles the replacement strings, so it will replace like AAA, BBB, CCC, AAA (again), etc. The exact strategy you wish to adopt may be different.
The second parameter to preg_replace_callback()
may also be a closure (>= 5.3)
Also, instead of using a regular function with static
declarations, it might be more appropriate to use an object for state management.