PHP equivalent of Python `str.format` method?

Is there an equivalent python str.format in PHP?

In Python:

 "my {} {} cat".format("red", "fat") 

All that I see, I can do in PHP initially by naming entries and using str_replace :

 str_replace(array('{attr1}', '{attr2}'), array('red', 'fat'), 'my {attr1} {attr2} cat') 

Are there any other alternatives to PHP?

+8
python php replace
source share
2 answers

Since PHP really does not have a suitable alternative to str.format in Python, I decided to implement my very simple own, which, like most of the basic Python functionalities.

 function format($msg, $vars) { $vars = (array)$vars; $msg = preg_replace_callback('#\{\}#', function($r){ static $i = 0; return '{'.($i++).'}'; }, $msg); return str_replace( array_map(function($k) { return '{'.$k.'}'; }, array_keys($vars)), array_values($vars), $msg ); } # Samples: # Hello foo and bar echo format('Hello {} and {}.', array('foo', 'bar')); # Hello Mom echo format('Hello {}', 'Mom'); # Hello foo, bar and foo echo format('Hello {}, {1} and {0}', array('foo', 'bar')); # I'm not a fool nor a bar echo format('I\'m not a {foo} nor a {}', array('foo' => 'fool', 'bar')); 
  • Order doesn't matter
  • You can omit the name / number if you want it to just increment (the first {} will be converted to {0} , etc.),
  • You can name your parameters,
  • You can mix three other points.
+5
source share

sprintf is the closest thing. This is an old-style string formatting:

 sprintf("my %s %s cat", "red", "fat") 
+5
source share

All Articles