Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将字符串中的%xxx替换为$xxx?_Php_Regex - Fatal编程技术网

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

Php 如何将字符串中的%xxx替换为$xxx?,php,regex,Php,Regex,如何将字符串中的%xxx替换为$xxx <?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

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

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

您需要将替换值评估为php,因此您需要
e
修饰符(尽管从PHP5.5开始,它似乎已被弃用…)。您还需要一个量词,因为
$xx
包含多个字符:

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


顺便说一下,我更喜欢单引号,以避免php试图查找变量时出现问题。

为了以这种方式合并变量,您可能应该执行以下操作:

$b = preg_replace_callback("/(?<=%)\w+/",function($m) {
        return $GLOBALS[$m[0]];
    },A);
$replacements = array(
    "%a"=>"hello",
    "%xx"=>"jimmy"
);
$b = strtr(A,$replacements);

我不知道这是否有效,但是
“\${$1}”
可能有效?@Class可以在字符串中获得
$
,但它不会计算变量(即字符串中的
$a
应计算为
hello
)。不要说“我有错误”。总是说“这是我得到的错误”,然后告诉我们确切的错误。不要解释它。不要重新打字。完全从屏幕上剪切并粘贴错误消息。谢谢,我记得
/regex/
看起来更好。特别是当正则表达式中没有``符号时。