Improved sprintf for PHP

Does anyone know the best sprintf implementation in PHP? I was looking for something like string formatting in python:

print "Hello %(name)s. Your %(name)s has just been created!" % { 'name' : 'world' } # prints::: Hello world. Your world has just been created! 

This is very convenient to avoid repeating the same variables without the need, for example:

 sprintf("Hello %s. Your %s has just been created!", 'world', 'world'); # prints::: Hello world. Your world has just been created! 

I think it's pretty easy to build it yourself, but don't try to reinvent the wheel if you know what I mean ... but I couldn't find (maybe the wrong search keywords) any traces of this anywhere.

If anyone can help, I appreciate.

Greetings

+4
source share
5 answers

You can use positional arguments (but not named) to do this, for example

 printf('Hello %1$s. Your %1$s has just been created!', 'world'); 

A word of caution here: you must use single quotes, otherwise dollar signs will cause PHP to try to replace $s with the value of this variable (which does not exist).

If you need named arguments, you will have to do this with a regular expression; for example, see How to replace placeholders with actual values? .

+8
source

You can repeat the same place with PHP sprintf (although this may not seem very nice):

 $str = sprintf('%1$s %1$s', 'yay'); // str: 'yay yay' 

You can use n$ immediately after % in the placeholder, where n is the position of the argument (therefore %1$s refers to the first argument (as a string), %2$s refers to the second, etc.). As you can see above, when you use landlords that are positionally attached, you can repeat them in a line without duplicating the arguments when sprintf called.

+5
source

The following code was stolen from a message from Salathe on TalkPHP .

 $szAdjective = 'fluffy'; $szNoun = 'cat'; printf('Yesterday, I saw a %s. '. 'It was a %s %s! I have '. 'never seen a %s quite so %s.', $szNoun, $szAdjective, $szNoun, $szNoun, $szAdjective); printf('Yesterday, I saw a %1$s. '. 'It was a %2$s %1$s! I have '. 'never seen a %1$s quite so %2$s.', $szNoun, $szAdjective); 

The above two expressions are equivalent and there will be both conclusions

"Yesterday I saw a cat. It was a fluffy cat! I never saw a cat so fluffy."

+3
source

I answered this question in another post: vsprintf or sprintf with named arguments or simple template analysis in PHP

But this is the same format you are looking for!

This is really the best way to go IMHO. No critical characters, just use key names!

As taken from php site: http://www.php.net/manual/en/function.vsprintf.php

 function dsprintf() { $data = func_get_args(); // get all the arguments $string = array_shift($data); // the string is the first one if (is_array(func_get_arg(1))) { // if the second one is an array, use that $data = func_get_arg(1); } $used_keys = array(); // get the matches, and feed them to our function $string = preg_replace('/\%\((.*?)\)(.)/e', 'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string); $data = array_diff_key($data,$used_keys); // diff the data with the used_keys return vsprintf($string,$data); // yeah! } function dsprintfMatch($m1,$m2,&$data,&$used_keys) { if (isset($data[$m1])) { // if the key is there $str = $data[$m1]; $used_keys[$m1] = $m1; // dont unset it, it can be used multiple times return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should } else { return "%".$m2; // else, return a regular %s, or %d or whatever is used } } $str = <<<HITHERE Hello, %(firstName)s, I know your favorite PDA is the %(pda)s. You must have bought %(amount)s HITHERE; $dataArray = array( 'pda' => 'Newton 2100', 'firstName' => 'Steve', 'amount' => '200' ); echo dsprintf($str, $dataArray); // Hello, Steve, I know your favorite PDA is the Newton 2100. You must have bought 200 
+2
source

I wrote a small component that allows you to do name replacements in php strings. It is called a StringTemplate . With it, you can get what you want with this code:

 $engine = new StringTemplate\Engine; $engine->render( '"Hello {name}. Your {name} has just been created!"', [ 'name' => 'world', ] ); //Prints "Hello world. Your world has just been created!" 

A multidimensional array value is also allowed. Hope this helps.

0
source

Source: https://habr.com/ru/post/1391751/


All Articles