Formatting strings is an essential part of preparing content for display in web pages, reports, messages, or user interfaces. PHP provides a wide range of functions to format, modify, clean, and style text so it appears neatly and correctly when shown to users.
Whether you want to change case, trim spaces, format numbers, or create structured output, PHP has built-in tools to help you present your data professionally.
What Is String Formatting?
String formatting refers to the process of modifying raw text into a clean, readable, and user-friendly form.
Some common formatting tasks include:
- Changing case (upper/lower)
- Removing unwanted spaces
- Formatting numbers, dates, and special strings
- Padding text
- Replacing parts of strings
- Creating formatted output (like email templates or UI text)
Common PHP String Formatting Functions
✔ 1. Changing String Case
$str = "welcome to SAVANKA";
echo strtolower($str); // welcome to savanka
echo strtoupper($str); // WELCOME TO SAVANKA
echo ucwords("php string formatting"); // Php String Formatting
✔ 2. Trimming Unwanted Spaces
$text = " Hello PHP ";
echo trim($text); // Removes both sides
echo ltrim($text); // Removes left spaces
echo rtrim($text); // Removes right spaces
✔ 3. Formatting with printf() and sprintf()
These functions are used to create clean, formatted output.
Using printf()
$price = 99.5;
printf("Price: %.2f", $price); // Price: 99.50
Using sprintf() (returns formatted string)
$name = "Sagar";
$message = sprintf("Hello %s, welcome!", $name);
echo $message;
✔ 4. Padding Strings
Used to align text in tables or lists.
echo str_pad("PHP", 10, ".", STR_PAD_RIGHT);
// Output: PHP.......
✔ 5. Replacing Parts of Strings
echo str_replace("PHP", "Python", "I love PHP programming!");
// I love Python programming!
✔ 6. Formatting Numbers
echo number_format(12345.678, 2);
// Output: 12,345.68
✔ 7. Escaping Special Characters for Safe Display
echo htmlspecialchars("<h1>Hello</h1>");
// <h1>Hello</h1>
Useful for preventing HTML injection in output.
✔ 8. Multi-line String Formatting (Heredoc / Nowdoc)
$message = <<<TEXT
Hello User,
Welcome to PHP string formatting.
Thank you!
TEXT;
echo $message;
Why Formatting Strings Is Important?
- Improves readability
- Ensures professional UI presentation
- Prepares data for display or reports
- Helps prevent layout breaking
- Makes content user-friendly
- Helps sanitize output for security
Real-World Examples
✔ Displaying prices in an eCommerce store
✔ Showing names with proper capitalization
✔ Formatting user-generated content
✔ Creating formatted invoices or receipts
✔ Preparing email templates
Citations
🔗 View other articles about PHP:
http://savanka.com/category/learn/php/
🔗 External PHP Documentation:
https://www.php.net/manual/en/