用句子替换不同值的单词

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.

Take a look at preg_replace if you are familiar with regular expressions. http://php.net/manual/en/function.preg-replace.php

$pattern =array("{pattern1}","{pattern2}","{pattern3}");
$replace=array("aaaaa","bbbbb","ccccc");
$string="{pattern1} test {pattern2} how r u {pattern3}";
$replaceme=str_replace($pattern,$replace,$string);

Use str_replace:

$haystack  = "{patternA} test {patternB} how are you {patternC}";
$search_for = array("{patternA}","{patternB}","{patternC}");
$replace_with   = array("{AAA}", "{BBB}", "{CCC}");

$new_string = str_replace($search_for, $replace_with, $haystack);

There are obviously multiple ways to achieve this but the most recommended one would be using regular expressions. They are well worth to learn but in case you don't have the time to learn it now, you can just look at a cheat sheet and make one that fits your needs for a specific task in a relatively short time.

You can use this code:

$str = '{pattern} test {pattern} how r u pattern {pattern}';
$repl = array('AAA', 'BBB', 'CCC');
$tok = preg_split('~(?<={)pattern(?=})~', $str);
$out = '';
for ($i=0; $i<count($tok); $i++)
   $out .= $tok[$i] . $repl[$i];
var_dump($out);

OUTPUT

string(38) "{AAA} test {BBB} how r u pattern {CCC}"
$values = array(
  'aaa', // first match
  'bbb', // second match
  'ccc'  // third match
);

$subject = '{pattern} test {pattern} how r u {pattern}';

$replaced = preg_replace_callback('/\{(.*?)\}/', function($matches) use ($values) { static $i = 0; return $values[$i++];  }, $subject);

echo $replaced;