如何在字符串中将%xxx替换为$ xxx?

how to replace %xxx to be $xxx in string ?

<?php
// how to replace the %xxx to be $xxx

define('A',"what are %a doing, how old are %xx ");
$a='hello';
$xx= 'jimmy';
$b= preg_replace("@%([^\s])@","${$1}",A);   //error here;

// should output: what are hello doing,how old are jimmy
echo $b;

?>

You need to evaluate the replacement value as php, so you need the e modifier (although it seems it is deprecated as of php 5.5...). You also need a quantifier as $xx contains more than one character:

$b= preg_replace('@%([^\s]+)@e','${$1}',A);
                          ^  ^

See the working example on codepad.

By the way, I prefer single quotes to avoid problems with php trying to look for variables.

In order to incorporate variables in this manner, you should probably do something like this:

$b = preg_replace_callback("/(?<=%)\w+/",function($m) {
        return $GLOBALS[$m[0]];
    },A);

Note, however, that using $GLOBALS is generally a bad idea. Ideally, you should have something like this:

$replacements = array(
    "%a"=>"hello",
    "%xx"=>"jimmy"
);
$b = strtr(A,$replacements);