String formatting in PHP offers various methods to format and manipulate strings. Let's explore some common string formatting tasks.
```php
<?php
class Point {
public $x, $y;
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
}
// Create an instance of our Point class
$p = new Point(1, 2);
// PHP offers several ways to format strings. One common method is using sprintf()
echo sprintf("struct1: %s\n", print_r($p, true));
// To include object properties, we can use json_encode()
echo sprintf("struct2: %s\n", json_encode($p));
// For a more detailed representation, we can use var_export()
echo sprintf("struct3: %s\n", var_export($p, true));
// To print the type of a value, use gettype()
echo sprintf("type: %s\n", gettype($p));
// Formatting booleans
echo sprintf("bool: %s\n", $true ? 'true' : 'false');
// Formatting integers
echo sprintf("int: %d\n", 123);
// PHP doesn't have a built-in binary format specifier, but we can use decbin()
echo sprintf("bin: %s\n", decbin(14));
// To print a character by its ASCII value
echo sprintf("char: %c\n", 33);
// Hexadecimal encoding
echo sprintf("hex: %x\n", 456);
// Formatting floats
echo sprintf("float1: %f\n", 78.9);
// Scientific notation
echo sprintf("float2: %e\n", 123400000.0);
echo sprintf("float3: %E\n", 123400000.0);
// Basic string printing
echo sprintf("str1: %s\n", '"string"');
// PHP doesn't have a built-in way to double-quote strings in output, but we can use addslashes()
echo sprintf("str2: \"%s\"\n", addslashes('"string"'));
// Hexadecimal representation of a string
echo sprintf("str3: %s\n", bin2hex("hex this"));
// PHP doesn't have a direct equivalent to Go's pointer printing, but we can print the object's hash
echo sprintf("pointer: %s\n", spl_object_hash($p));
// Controlling width for integers
echo sprintf("width1: |%6d|%6d|\n", 12, 345);
// Controlling width and precision for floats
echo sprintf("width2: |%6.2f|%6.2f|\n", 1.2, 3.45);
// Left-justifying floats
echo sprintf("width3: |%-6.2f|%-6.2f|\n", 1.2, 3.45);
// Controlling width for strings
echo sprintf("width4: |%6s|%6s|\n", "foo", "b");
// Left-justifying strings
echo sprintf("width5: |%-6s|%-6s|\n", "foo", "b");
// Using sprintf to return a formatted string
$s = sprintf("sprintf: a %s", "string");
echo $s . "\n";
// Writing to a different output stream
file_put_contents('php://stderr', sprintf("io: an %s\n", "error"));