[英]Is it possible to reference a variable before defining it?
A very simplified version of what I am trying to do: 我想要做的非常简化的版本:
$quote = "Currently showing number $i";
for($i=0;$i<100;$i++){
echo $quote;
}
Where the $i
from $quote
is constantly updated with the new value. 来自
$quote
的$i
不断更新新值。
Again this is a simplified example. 这又是一个简化的例子。 I realize it could be reordered to accomplish the same thing or a
str_replace()
used, but for the real code it could not be accomplished. 我意识到它可以重新排序以完成相同的事情或使用的
str_replace()
,但对于真正的代码,它无法完成。
I would just do something like: 我会做的事情如下:
$quote = "Currently showing number ";
for($i=0;$i<100;$i++){
echo $quote.$i;
}
Here is your answer 这是你的答案
<?php
$quote = 'Currently showing number $i';
$pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';
preg_match_all($pattern, $quote, $matches);
for ($i=0; $i<100; $i++) {
foreach ($matches[1] as $index => $valName) {
if (isset(${$valName})) {
$result = str_replace($matches[0][$index], ${$valName}, $quote);
}
}
echo $result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.