M
M
Maxim Ivanov2015-09-28 20:52:50
PHP
Maxim Ivanov, 2015-09-28 20:52:50

How to replace a variable in text?

Let's say we have a script

<?php
$var = "значение";
$text = 'more text $var'; // не двойные кавычки, php не подменит
?>

How to replace the text in a variable with our variable, while we do not know the exact name of the variable, how to do it all the same?
I ask for your algorithms...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivanq, 2015-09-28
@omaxphp

Not very fast, but:

foreach($GLOBALS as $k=>$v) {
    $text = str_replace('$'.$k, $v, $text);
}

If there are several variables, you can simply write
$text = str_replace('$var', $var, $text);
$text = str_replace('$var2', $var2, $text);
$text = str_replace('$var3', $var3, $text);

PS I did not check, do not judge strictly :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question