Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.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 key=>;中替换var{$key};奥鲁_Php - Fatal编程技术网

如何在数组php key=>;中替换var{$key};奥鲁

如何在数组php key=>;中替换var{$key};奥鲁,php,Php,我需要一个助手 关于简单变量的替换: $html = '<{$headtype} class="{$class}">{$text}</{$headtype}>'; $array['headtype'] = 'h1'; $array['class'] = 'classname'; $array['text'] = 'the title'; // result <h1 class="classname">the title</h1>

我需要一个助手

关于简单变量的替换:

$html = '<{$headtype} class="{$class}">{$text}</{$headtype}>';
$array['headtype']  = 'h1';
$array['class']     = 'classname';
$array['text']      = 'the title'; 
// result
<h1 class="classname">the title</h1>
$html='{$text}';
$array['headtype']='h1';
$array['class']='classname';
$array['text']='thetitle';
//结果
标题
知道数组的键和值是可变的

$array['headtype']='h1';
$array['headtype']  = 'h1';
$array['class']     = 'classname';
$array['text']      = 'the title'; 
extract($array)
$html = '<{$headtype} class="{$class}">{$text}</{$headtype}>';
$array['class']='classname'; $array['text']='thetitle'; 提取($array) $html='{$text}';
如果我答对了,这就是你想要的。请在下面发表评论,我将根据您的需要更新我的答案。

$array['headtype']='h1';
$array['class']='classname';
$array['text']='thetitle';
提取($array)
$html='{$text}';

如果我答对了,这就是你想要的。请在下面发表评论,我将根据您的需要更新我的答案。

您可以像这样将数组键和旧键设置为unset,
$arr[$newkey]=$arr[$oldkey];未设置($arr[$oldkey])
更多信息,您可以查看下面的文章。

您可以像这样将数组键和旧键设置为unset,
$arr[$newkey]=$arr[$oldkey];未设置($arr[$oldkey])
更多信息,您可以查看下面的文章。

只需遍历数组并使用替换字符串:

foreach ($array as $key => $value) {
    $html = str_replace('{$'.$key.'}', $value, $html);
} 

演示:

只需迭代数组并使用替换字符串:

foreach ($array as $key => $value) {
    $html = str_replace('{$'.$key.'}', $value, $html);
} 

演示:

这并不能真正回答问题。您仍然需要在字符串中替换它们(OP实际上是在询问这个问题)。如果您试图解析字符串中的变量,则需要将字符串用双引号括起来。感谢您的回复,我将在几分钟内更新我的答案。我还建议不要使用
extract()
,因为它会使变量范围混乱,并可能导致不需要的结果(如果作用域已经包含这些变量中的任何一个)。感谢geekido..使用了extract($array);$press=preg\u replace('/\{\$([a-z]+)\}/e',“$$1',$html);结果正如我所希望的,如果你有更好的代码,我希望你能给我们带来好处Hank you@HossamMega我一直在搜索,当我发现更好的代码时,我会更新。这并不能真正回答问题。你仍然需要在字符串中替换它们(这就是OP实际询问的问题)。如果您试图解析字符串中的变量,则该字符串需要用双引号括起来。感谢您的答复,我将在几分钟内更新我的答案。我还建议不要使用
extract()
,因为它会使变量范围混乱,并可能导致不必要的结果(如果作用域已经包含这些变量中的任何一个)。感谢geekido..Used extract($array);$press=preg_replace('/\{\$([a-z]+)\}/e',“$$1”,$html);结果正如我所希望的,如果您有更好的代码,我希望您能为我们带来好处谢谢您@HossamMega我一直在搜索,当我找到更好的代码时,我会更新