简体   繁体   中英

How to save a PHP string with variable not explicit?

I have an array like this:

$list = array (
  "Today is ".$aaaa."/".$mm."/".$gg,
  "Oggi è il ".$gg."/".$mm."/".$aaaa,
  "Aujourd'hui, c'est ".$gg."/".$mm."/".$aaaa
);

I would like to save them in a database (with variables not explicit) and then re-use them in php format. Is it possible to save as string a string in php format?

Example:

$gg = 1;
$myString = "Today is ".$gg;
echo $myString;

$gg = 17;
echo $myString;

This example, of course, show always "Today is 1". I would like it show "Today is 1", "Today is 17". Can I save myString with variables not explicit?

使用sprintf()并保存格式。

use printf

$myString = "Today is %s";

$today = '21/12/2012';
printf($myString,$today); // Today is 21/12/2012

$today = 21;
printf($myString,$today); // Today is 21

printf will output directly the string. sprintf will return it

EDIT: in your specific case you should specific the order

$list = array (
  'Today is %1$s/%2$s/%3$s',
  'Oggi è il %3$s/%2$s/%1$s',
  'Aujourd\'hui, c\'est %3$s/%2$s/%1$s'
);

foreach($list as $string) {
    printf($string,"2012","12","21");
    echo  " <br />";
}

However for localization I would use the setlocale function for simple strings and strftime (with setlocale) for localized dates

Can I save myString with variables not explicit?

Sort of, yes. You can implement that:

class MyStringVariable
{
    private $mask;
    private $variables;

    public function __construct($mask, array $variables) {
        $this->mask = $mask;
        $this->variables = $variables;
    }

    public function __toString() {
        return vsprintf($this->mask, $this->variables);
    }
}

Usage ( Demo ):

$gg = 1;
$myString = new MyStringVariable("Today is %s\n", [&$gg]);
echo $myString;

$gg = 17;
echo $myString;

Output:

Today is 1
Today is 17

This works basically by wrapping vsprintf (see sprintf ) into an object of it's own that also stores the variable references you want to make use of. The magic __toString method takes care of resolving the output when it is needed.

$sql = 'My var is %s';

$a = 100;
$foo = sprintf($sql, $a);

EDIT 1;

$list = array(
    "Today is %s/%s/%s",
    "Oggi è il %s/%s/%s",
    "Aujourd'hui, c'est %s/%s/%s"
);

foreach ($list as $str)
{
    $a   = 2012;
    $m   = 12;
    $g   = 17;

    if (strstr($str, 'Today '))
        $foo = sprintf($str, $a, $m, $g);
    else
        $foo = sprintf($str, $g, $m, $a);
}

I don´t know if this is the best way but it works, you save the lines as strings, and with eval() then convert to variables

$list = array (
    'Today is ".$aaaa."/".$mm."/".$gg'
);
$aaaa = 2012;
$mm = 11;
$gg = 00;
eval("\$mylist = \"$list[0];");
echo $mylist;

Happy coding !!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM