Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Sandman Newsgroups: comp.lang.php Subject: Re: variable replacement in string Date: Fri, 11 May 2012 16:06:37 +0200 Lines: 103 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Trace: individual.net W8WVnYslxUBhmDYuYTKvJArbJfIdAxCUNA54/SmL7SylqHGLWYSsBEwCLIowYlXmg= X-Orig-Path: mr Cancel-Lock: sha1:dcj1X/zHT0WctdtP+pHk5hl5flM= User-Agent: MT-NewsWatcher/3.5.2 (Intel Mac OS X) X-Face: $@,Vfa$,)%=Qa7L]y)&oZj_\EiHc}}Af0Bei"4a_%)"c6TQ+P/:53>;PNGuWUmkqyeN-qM65foJ[;T_(k;>]&G\T4Lhm:2 ujye2_,iUJFE;NZn>y;.|-hl7g~bIOF1qG\o, MuahMan, Redjak, isquat@gmail.com, Robert Whelan, jt2002a@hotmail.com Xref: csiph.com comp.lang.php:5964 In article , "M. Strobel" wrote: > Am 10.05.2012 15:05, schrieb Goran: > > On 10.5.2012 14:44, 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. > > > > strtr() ? > > > > You could do something like this: > > > > $template = 'Your name is %given_name% %family_name%'; > > > > echo strtr($template, array( > > '%given_name%' => 'John', > > '%family_name%' => 'Doe', > > )); > > yeah, create my own variable system. No easier way? > > /Str. TESTED: #!/usr/bin/php Of course, having posted that, I'd still use caution with scopes and globilzation of variables, since this function may be called inside another function which hasn't globalized $t, so I would still recommend to send along a variables of values: #!/usr/bin/php And using single quotes when creating the template is important as well, since we're using PHP-style variables. If you have your own variable denotation, you don't have to think about that at all (see my earlier parserxml() function) -- Sandman[.net]