Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!not-for-mail From: "M. Strobel" Newsgroups: comp.lang.php Subject: Re: variable replacement in string Date: Thu, 10 May 2012 18:29:33 +0200 Lines: 53 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de Q7XsNk+BrxVxjW8WtKEtNgIO6PwHeCMwBQiWzH1XRf+cyV+OcNJ6QiLc/lddaw2Ko= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20120421 Thunderbird/12.0 In-Reply-To: Xref: csiph.com comp.lang.php:5926 Am 10.05.2012 15:14, schrieb Jerry Stuckle: > On 5/10/2012 8:44 AM, M. Strobel wrote: >> Hi, >> >> I am still searching a function in PHP to execute variable replacement in strings. >> Other languages do have this, but for PHP I can only find sprintf() and string >> replace. >> >> I have >> >> $t = ' - solved - '; >> $msg = 'The problem is $t'; >> >> I want now: >> >> echo fxx($msg); >> >> print out "The problem is - solved - ". >> >> Please don't tell me about $msg = "The problem is $t"; just think of $msg like a >> template read from a file. >> >> /Str. > > There's also preg_replace(), but that's a bit of overkill for something so simple. > > str_replace() works fine, especially since both the search and replace parameters can > be arrays. But when using message templates, I don't use variable names - it ties > the template tightly to the code. > > Rather, I use templates like: > > $t = ' - solved - '; > $template = 'The problem is %PROB_STAT%'; > echo str_replace('%PROB_STAT%', $t, $template); > > Or, if you had the possibility of more than one string to substitute: > > $search = array('$PROB_STAT%'); > $replace = array($t); > echo str_replace('%PROB_STAT%', $t, $template); > > Your method requires the template know that $t is the value in the program, and > requires the program to ensure $t is defined properly in this scope. Neither is a > good idea. > I see the problem of the undefined $t. Think of my method as "do what double quotes do". It may well not exist, maybe I file a feature request. /Str.