如何将字符串转换为变量并仍然获得良好的输出

时间:2017-10-27 08:31:44

标签: php output echo

如何将字符串转换为变量并仍然获得良好的输出。

$text = "showandreturn";

$disp = str_split($text, 2); 

$firstnum = 3;

for($b = 0; $b<$firstnum; $b++){

    $a = "$disp[$b]"; #showan

}

$b = "ENDED";

for($b = $firstnum; $b<sizeof($disp); $b++){

    $c = "$disp[$b]"; #dreturn

    echo = "$a$b$c";
}

此代码的当前输出是。 andranetanurann .. 我想要像showanENDEDdreturn

这样的结果

感谢您的时间和理解..

3 个答案:

答案 0 :(得分:0)

您是否尝试将ENDED置于字符串的中间?
在这种情况下看看这个:

$text = "showandreturn";
$b = "ENDED";

$len = strlen($text); // lenght of string
// Output half string + $b + rest of string
Echo substr($text, 0, floor($len/2)) . $b . substr($text, floor($len/2));

https://3v4l.org/Ea6tn

答案 1 :(得分:-1)

备选方案1

您需要的是variables variable

$foo = 'bar';
$foo = 'magic';

echo $foo; //Outputs magic

备选方案2:

您可以查看http://php.net/manual/en/function.parse-str.php

parse_str($"My Value=Something");
echo $My_Value; // Something

备选方案3:

echo eval('return $'. $string . ';');

答案 2 :(得分:-1)

每次循环时都会覆盖变量,因此只有最后一个循环的结果存储在变量中。

此代码应返回所需的输出。

$text = "showandreturn";
$disp = str_split($text, 2);
$num = 3;
$a = '';
$c = '';
for($b = 0; $b<$num; $b++){
    $a .= $disp[$b];
}
$b = "ENDED";
for($bn = $num; $bn<sizeof($disp); $bn++){
    $c .= $disp[$bn];
}
echo $a.$b.$c;